I have a Web for that requires the user to enter a date which is then stored in a MySQL database. I'd like to have the user enter the date in m/d/yyyy and have the system convert it into the Y-m-d format that MySQL requires. I thought that was simple enough, but I can't get it to stop making a serious error,
I've tried the following:
$date = new DateTime($this->vital_date);
$this->vital_date = $date->format('Y-m-d');
When the user enter 9/6/2013, 2013-06-09 gets stored in the MySQL table. (Note the transposition of the month and date.
Then, I tried the older, pre-object way:
$date = strtotime($this->vital_date);
$this->vital_date = date('Y-m-d', $date);
And that did the same thing -- a transposed month and date.
Can anyone give me any help on what I'm doing wrong or how I could make a better conversion.
You should use DateTime::createFromFormat for non-standard format
You should be using DateTime::createFromFormat
From PHP DOC
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
Example
$vital_date = "9/6/2013";
$date = DateTime::createFromFormat("m/d/Y", $vital_date);
echo $date->format('Y-m-d');
You can specify the format you are giving the data in the following way:
$date = DateTime::createFromFormat('j/n/Y', '9/6/2013');
This sample is not just obvious for this situation but it is even useful in many other places too for eg getting info from an mathematician entered quadratic equation in your site text box without regex
or driving licence number can be properly handled and stored in a database formatting it using scanf
for eg scanf($input, '%s-%s-%d/%d)
; etc
it depends on your need so you have to know about sscanf
, scanf
, printf
, sprintf
, vsprintf
<?php
$date = '9/6/2013';
list($month,$day,$year) = sscanf($date, '%d/%d/%d');
$date = sprintf('%d-%02d-%02d',$year,$month,$day);
echo $date;
?>