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 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?