Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DateTime::createFromFormat doesn't parse ISO 8601 date time

Tags:

php

datetime

Code speaks a million words:

php > echo strtotime("2010-12-07T23:00:00.000Z"); 1291762800 echo date('c', 1291762800); 2010-12-08T00:00:00+01:00 php > var_dump(DateTime::createFromFormat('c', "2010-12-07T23:00:00.000Z")); bool(false) php > var_dump(DateTime::createFromFormat(DateTime::ISO8601, "2010-12-07T23:00:00.000Z")); bool(false) 

Any idea what's going on?

Btw, yes, new DateTime("2010-12-07T23:00:00.000Z") works fine. But I prefer to know what input I am getting.

like image 896
Jake Avatar asked Dec 10 '10 16:12

Jake


People also ask

How do I read the ISO 8601 date format?

ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).

What time zone is ISO 8601?

Time zones in ISO 8601 are represented as local time (with the location unspecified), as UTC, or as an offset from UTC.


2 Answers

Parsing ISO8601 date, and also switching timezone:

// create ISO8601 dateTime  $date = DateTime::createFromFormat(DateTime::ISO8601, '2016-07-27T19:30:00Z');  // set to user's timezone $date -> setTimeZone('Asia/Singapore');  echo $date -> format(DateTime::ISO8601); // prints '2016-07-28T03:30:00+0800' 
like image 38
a20 Avatar answered Sep 20 '22 17:09

a20


There's a bug report that exactly describes your problem :)

https://bugs.php.net/bug.php?id=51950

Since 2016-08-07, the bug report has been marked as "not a bug". You need to use strtotime or new DateTime instead.

The constants that have been defined apply to both formatting and parsing in the same way, which forces your ways.

like image 65
Ja͢ck Avatar answered Sep 20 '22 17:09

Ja͢ck