douxiong0668 2011-04-27 15:07 采纳率: 100%
浏览 165
已采纳

DateTime :: getTimezone不返回时区名称,而是返回偏移量

<?php
$first = '2011-04-27';
$second = '2011-04-27 16:20:12';
$third = '2011-04-27 16:20:12+00';

$dt = new DateTime($first);
$dt->setTimeZone(new DateTimeZone($dt->getTimeZone()->getName()));
echo $dt->getTimezone()->getName().'<br />';
// OK
$dt = new DateTime($second);
$dt->setTimeZone(new DateTimeZone($dt->getTimeZone()->getName()));
echo $dt->getTimezone()->getName().'<br />';
// OK
$dt = new DateTime($third);
$dt->setTimeZone(new DateTimeZone($dt->getTimeZone()->getName()));
echo $dt->getTimezone()->getName().'<br />';
// Error
// ->getName() returns unexpectedly +00, which is not a name, but offset

DateTime extracts from the last string timezone name +00, which is really not name, but offset and therefore cannot be set as timezone...

This behavior is causing troubles when (de)serializing DateTime object...

public function __sleep()
{
    $this->fix = array($this->format('Y-m-d H:i:s'), $this->getTimezone()->getName());
    return array('fix');
}

public function __wakeup()
{
    $this->__construct($this->fix[0], new DateTimeZone($this->fix[1]));
    unset($this->fix);
}

I know it would be better to get e.g. this string: 2011-04-27 16:20:12 UTC, anyway as far as the metod is called getName(), it shouldn't return +00 as a name, or should?

  • 写回答

2条回答 默认 最新

  • dtrotfd1012 2011-04-27 15:23
    关注

    You have tried to create DateTime object with timezone offset +00, that's why it returned offset instead of valid timezone identifier and actually that means GMT+0000. Using datetime string without offset you'll get PHP timezone identifier according to current timezone setting in DateTime object (or system).

    With $third = '2011-04-27 16:20:12+00'; you have set +00:00 offset in DateTime object instead of PHP identifier and DateTime just returns that back with ->getName() method.

    Fixed offset doesn't provide information about DST rules so it can't be used to get back PHP TimeZone identifier. Example: In my zone it's GMT+2 at the moment (active DST) but if I put it in datetime string, DateTime object can't know when my offset changes to +1, simply, it's always GMT+0200... that's all.

    Offset +00 in your case matches a lot of different timezone identifiers like Atlantic/Reykjavík, Africa/Casablanca, Africa/Nouakchott, etc.

    That's why getName() method returns time offset instead of timezone!

    This is not official explanation, but that's it in short version.

    Of course, 2011-04-27 16:20:12+00 is not valid datetime string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘