首先,unix 时间戳始终采用 UTC,因此它没有时区和 DST。
另一方面,DateTime
对象存储当地时间 only (“本地”是指设置的时区DateTime
实例).
因此你应该将时区设置为+00:00 or UTC在设置时间戳之前,以避免不必要的时间转换和 DST 猜测。
你有两个选择:
1.通过构造函数设置时间戳DateTime
构造函数将覆盖默认时区并显式设置为+00:00当它得到时间戳时(开始于@
)在第一个参数中:
$set_timestamp = 1319932800;
$date = new DateTime('@' . $set_timestamp);
print($set_timestamp . "\n");
print($date->getTimestamp() . "\n");
信息:在这种情况下,构造函数的时区参数总是会被覆盖。
2. 通话前设置时区setTimestamp()
Call setTimezone()
with DateTimeZone('+00:00')
or DateTimeZone('UTC')
致电之前的时区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
当然,这两种情况的输出都是:
1319932800
1319932800
The date_default_timezone_set()
在这些情况下是不必要的,因为您不想用当地时间做任何事情。
但是,当您想打印$date
以人类可读的格式(所以当你将unix时间戳转换为本地时间时)时区将会再次变得有趣。