简体   繁体   中英

Convert Time to ISO 8601 format in UTC timezone

I have date as Fri, 15 Mar 2019 08:56:57 +0000

I want to convert this date in ISO 8601 format in UTC timezone in php.

I have tried the following:

$date = new DateTime("Fri, 15 Mar 2019 08:56:57 +0000");
$output = $date->format(\DateTime::ATOM);

Is this correct?

If you want the ISO 8601 format you should use the DateTimeInterface::ISO8601 in the format method, or you can use "c" :

$date = new DateTime("Fri, 15 Mar 2019 08:56:57 +0000");
echo $date->format(\DateTime::ISO8601);
// will be 2019-03-15T08:56:57+0000
echo $date->format("c");
/* 
will be 2019-03-15T08:56:57+00:00
note the : in between hh and mm in offset(timezone)
generally accepted as valid ISO 8061 see:
https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC
*/

Regarding the timezone if you want to force it into UCT timezone then you should use the setTimezone method on the date object first with timezone param "UTC" :

$date = new DateTime("Fri, 15 Mar 2019 08:56:57 +0000");
$date->setTimezone(new DateTimeZone("UTC"));
$output = $date->format(\DateTime::ISO8601);

Note about the above that if your original date time is not in UTC(has an offset) the time will be converted to UTC and the offset will be 0000:

$date = new DateTime("Fri, 15 Mar 2019 08:56:57 +0230");
echo $date->format(\DateTime::ISO8601);
// will be: 2019-03-15T08:56:57+0230
$date->setTimezone(new DateTimeZone("UTC"));
echo $date->format(\DateTime::ISO8601);
// will be: 2019-03-15T06:26:57+0000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM