我有一个时间戳,我正在尝试将其转换为另一个时区。这样做时我需要考虑夏令时。
我使用的代码如下:
$date = new DateTime("@".$timestamp);
echo $date->format('Y-m-d H:i:s')."\r\n";
$date->setTimezone(new DateTimeZone('Europe/Paris'));
echo $date->format('Y-m-d H:i:s')."\r\n"; // Pacific time
$date->setTimezone(new DateTimeZone('Europe/Athens'));
echo $date->format('Y-m-d H:i:s')."\r\n"; // Berlin time
输出(正确)是:
2014-01-30 20:24:48
2014-01-30 21:24:48
2014-01-30 22:24:48
但是,如果我将格式更改为“U”(Date() 中用于获取时间戳的值),则会输出以下内容:
1391113488
1391113488
1391113488
为什么时间戳没有应用时区偏移?
最佳答案
DateTime::getOffset
将为您提供以秒为单位的偏移量,DateTime::getTimestamp
将为您提供始终为 UTC 的 Unix 时间戳 (为您提供与 $datetime->format('U')
相同的内容)。
因此,为了获得带有偏移量的“时间戳”,请执行以下操作:
$timestampWithOffset = $date->getTimestamp() + $date->getOffset();
关于PHP DateTime 时间戳不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21467746/