DateTime object not bound by its timestamp?

寵の児 提交于 2019-12-04 09:36:53

First of all, the unix timestamp is always in UTC, so it hasn't timezone and DST.

In other hand, the DateTime object stores local time only (the "local" means what timezone is set in the DateTime instance).

Therefore you should set timezone to +00:00 or UTC before you set a timestamp for avoid unnecessary time conversions and DST guessing.

You have two choices:

1. Set timestamp via constructor of DateTime

The constructor will overrides the default timezone and explicit set to +00:00 when it got timestamp (started with @) in first parameter:

$set_timestamp = 1319932800;
$date = new DateTime('@' . $set_timestamp);

print($set_timestamp . "\n");
print($date->getTimestamp() . "\n");

Info: in this case, the timezone parameter of constructor always will be overridden.

2. Set timezone before call setTimestamp()

Call setTimezone() with DateTimeZone('+00:00') or DateTimeZone('UTC') timezone before you call setTimestamp():

$set_timestamp = 1319932800;
$date = new DateTime();
$date->setTimezone(new DateTimeZone('UTC'));
$date->setTimestamp($set_timestamp);

print($set_timestamp . "\n");
print($date->getTimestamp() . "\n");

Notes

Of course, both of these cases the output will be:

1319932800
1319932800

The date_default_timezone_set() is unnecessary in these cases, because you don't want to do anything with local time.

However when you want to print the $date in human readable format (so when you convert the unix timestamp to local time) the timezone will be interesting again.

\DateTime object doesn't keep timestamps but local time, and do conversions in timestamp getter and timestamp setter.

It results with a side-effect once a year when DST is being switched off, since both timestamp ranges 1319932800..1319936400 and 1319936400..1319940000 resolve to the same local time:
https://www.epochconverter.com/timezones?q=1319936399&tz=Europe%2FBerlin https://www.epochconverter.com/timezones?q=1319939999&tz=Europe%2FBerlin

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