RFC 3339 how make a dateTime from

旧时模样 提交于 2019-12-30 18:06:11

问题


I'm trying to format a date passed from a google plus Api thats like the guide says in RFC 3339 format:

PUBLISHED-> datetime-> The time at which this activity was initially published. Formatted as an RFC 3339 timestamp.

So by php documentation i found that:

DATE_RFC3339 Same as DATE_ATOM (since PHP 5.1.3)

And that both format are something like:

"Y-m-d\TH:i:sP"

Actually the output of the Google api is something like:

2014-01-22T10:36:00.222Z

When I'm trying to launch command like:

$date = DateTime::createFromFormat("Y-m-d\TH:i:sP", $activity['published']); //$activity['published'] contain the  date

I have always FALSE as return. In my opinion the problem is in the final part

.222Z

any suggestion will be appreciate before cutting it by some rudimental approach...


回答1:


You don't need to use DateTime::createFromFormat() for standard inputs. Just use:

$date = new DateTime('2014-01-22T10:36:00.222Z');
var_dump($date);

But if you still insist to use createFromFormat(), then use correct format, with microseconds:

$date = DateTime::createFromFormat('Y-m-d\TH:i:s.uP', '2014-01-22T10:36:00.222Z');
var_dump($date);



回答2:


There is a trick. A special constant DATE_RFC3339 was made to help, but it does not work if the last character is "Z" - which is perfectly fine for rfc3339 format. Actually JSON would specify format like that:

expected format YYYY-MM-DDThh:mm:ssZ or YYYY-MM-DDThh:mm:ss+hh:mm

But using this DATE_RFC3339 you can receive an Error message from PHP:

InvalidArgumentException: The timezone could not be found in the database

That is why we need to specify format manually:

With DateTime

$date = DateTime::createFromFormat ( 'Y-m-d\TH:i:s.u\Z' ,$time);

With Carbon:

\Carbon\Carbon::createFromFormat('Y-m-d\TH:i:s.u\Z',$time);


来源:https://stackoverflow.com/questions/21383088/rfc-3339-how-make-a-datetime-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!