PHP - 奇怪的时区偏移
我遇到了一个我无法理解的愚蠢问题。 为什么下面这段代码:
public function getFormattedOffsetFrom($refTimezoneId = 'Europe/Paris', $format = 'G\hi') {
$timestamp = time();
$reference = new DateTime('@'.$timestamp);
$referenceTimeZone = new DateTimeZone($refTimezoneId);
$reference->setTimezone($referenceTimeZone);
$datetime = new DateTime('@'.$timestamp);
$datetime->setTimezone($this->timezone);
$offset = $this->timezone->getOffset($datetime) - $referenceTimeZone->getOffset($reference);
$prefix = '+';
if($offset < 0) {
$prefix = '-';
$offset = abs($offset);
}
return $prefix.date($format, $offset);
}
其中 $this->timezone 是位于欧洲/马德里的 DateTimeZone 实例,在未指定参数时生成 +1h00 ????
巴黎和马德里没有时间偏移。我只是不明白。
非常感谢您的帮助!!!! 弗洛朗
I'm encountering a stupid problem which I just cannot understand.
How come that following piece of code:
public function getFormattedOffsetFrom($refTimezoneId = 'Europe/Paris', $format = 'G\hi') {
$timestamp = time();
$reference = new DateTime('@'.$timestamp);
$referenceTimeZone = new DateTimeZone($refTimezoneId);
$reference->setTimezone($referenceTimeZone);
$datetime = new DateTime('@'.$timestamp);
$datetime->setTimezone($this->timezone);
$offset = $this->timezone->getOffset($datetime) - $referenceTimeZone->getOffset($reference);
$prefix = '+';
if($offset < 0) {
$prefix = '-';
$offset = abs($offset);
}
return $prefix.date($format, $offset);
}
where $this->timezone is an instance of DateTimeZone positioned in Europe/Madrid, produces +1h00 when no args are specified ????
Paris and Madrid have no time offset. I just don't understand.
Thanks a lot for your help !!!!
Florent
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么应该是0?西班牙和法国都使用 GMT+1 作为时区。http:// en.wikipedia.org/wiki/File:Time_zones_of_Europe.svg
问题是您正在尝试使用函数
date() 格式化以秒为单位保存时差的
,它需要时间戳作为第二个参数。如果$offset
$offset == 0
date
函数将其识别为 1970-01-01 00:00:00 GMT,那么在您的时区中将是 1970-01-01 01:00:00 GMT+1,并且您正在使用格式返回小时和分钟,因此这就是您将 +1 作为输出的原因。您必须手动设置该时间差的格式,如下所示:
Why should be 0 ? Both Spain and France are using GMT+1 as time zone.http://en.wikipedia.org/wiki/File:Time_zones_of_Europe.svg
The problem is that you are trying to format
$offset
that holds time difference in seconds, with functiondate()
, which expects timestamp as second parameter. If the$offset == 0
date
function recognizes it as 1970-01-01 00:00:00 GMT, so in your timezone it will be 1970-01-01 01:00:00 GMT+1, and you are using format to return hours and minutes so that is why you have +1 as output.You have to manually format this time difference like this:
该问题可以简化为
date('G', 0)
给出“1”。解决方案是使用gmdate()
。The problem can be reduced to
date('G', 0)
giving "1". Solution is to usegmdate()
.