I have a user input in web-form in HTML5 type="date"
field. Then this entered value (together with others) is saved as JSON document in MySQL database. Now I need to extract that date and print it into generated MS Word document with one given format. Great! But as you know HTML5 date field accepts date format depending on user locales, settings, etc. I noticed that all dates entered in different browsers are saved in DB in "Y-m-d" format. Is this really so in all the cases? Can I rely on this format for future usage? Could not find any specification information on the topic. If one can not rely on "Y-m-d" format are there any PHP libraries for "guessing" date format?
First of all, why are you saving JSON document in MySQL database instead of some more suitable document database (e.g. MongoDB)?
Anyway, based on this and this the displayed date format differs from the actual value. The date value in the HTTP Request will be always formatted as yyyy-mm-dd
, which is the ISO 8601 format and I guess it should be reliable.
In PHP you can process date strings with the DateTime class. This class supports many different date formats. For example:
// timezone is set based on your system preferences if not set
$date1 = new DateTime('2017-04-27', new DateTimeZone('+00:00'));
$date2 = new DateTime('27 April 2017', new DateTimeZone('+00:00'));
$date3 = new DateTime('2017-04-27T00:00:00+00:00');
var_dump($date1 == $date2); // bool(true)
var_dump($date1 == $date3); // bool(true)
If the date string is wrong, an exception is thrown:
try {
$date = new DateTime('2017 4 27');
} catch (Exception $e) {
echo $e->getMessage(); // DateTime::__construct(): Failed to parse time string (2017 4 27) at position 5 (4): Unexpected character
}
So, in your case you can you this class for date validation and than proper output formatting, e.g.:
$dateString = '2017-04-27T14:22:11+00:00';
try {
$date = new DateTime($dateString);
echo $date->format('Y-m-d'); // 2017-04-27
} catch (Exception $e) {
// do something else
}