简体   繁体   中英

How to properly covert timestamp to ISO 8601 in PHP?

I'm getting the timestamp from http://www.unixtimestamp.com/index.php

So for 2016/1/1 @ 1:1:1 the timestamp should be 1451610061 which is equivalent to 2016-01-01T01:01:01+00:00 in ISO 8601 (from the site), but when I run the code below I would get the output of 2016-01-01T02:01:01+01:00 instead. Am I missing something?

$ts = 1451610061;
echo date('c', $ts);

This is clearly a timezone issue, as can be seen from "+00:00" vs "+01:00".

You can also verify this by setting the default timezone before with date_default_timezone_set

date_default_timezone_set("UTC");

2016-01-01T01:01:01+00:00

See eval.in - UTC

vs

date_default_timezone_set("Europe/Berlin");

2016-01-01T02:01:01+01:00

See eval.in - Berlin


You can also find out about your local timezone with date_default_timezone_get

echo date_default_timezone_get();

eval.in - local timezone

UTC

Which also explains why http://eval.in shows the expected output.


Of course, you can set the timezone on a DateTime object individually

$ts = 1451610061;
$dt = new DateTime("@$ts");

$utc = new DateTimeZone("UTC");
$dt->setTimezone($utc);
echo "UTC=", $dt->format('c'), "\n";

$berlin = new DateTimeZone("Europe/Berlin");
$dt->setTimezone($berlin);
echo "Berlin=", $dt->format('c'), "\n";

This will show

UTC=2016-01-01T01:01:01+00:00
Berlin=2016-01-01T02:01:01+01:00

eval.in - setTimezone


To finally answer your question: there's nothing wrong with your code. 2016-01-01T02:01:01+01:00 is a perfectly valid representation of this timestamp according to ISO 8601 - Wikipedia .

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