PHP的DateTime默认时区

4

最近我开始在PHP中使用DateTime对象,但现在我还不能弄清楚这个问题。

我以为DateTime会考虑我使用date_default_timezone_set设置的默认时区,但显然它并没有:

date_default_timezone_set('Europe/Oslo');
$str = strtotime('2015-04-12');
$date = new DateTime("@".$str);
$response['TZ'] = $date->getTimezone()->getName();
$response['OTZ'] = date_default_timezone_get();
$response['Date'] = $date->format('Y-m-d');

echo json_encode($response);

这是我所收到的响应:
{
  "TZ":"+00:00",
  "OTZ":"Europe\/Oslo",
  "Date":"2015-04-11"
}

将正确的DateTimeZone传递给构造函数也不起作用,因为当给定UNIX时间戳时,DateTime会忽略它。(如果我传递常规日期字符串到构造函数,则可以正常工作)。

如果我这样做,日期就会显示正确:

$date->setTimezone(new DateTimeZone("Europe/Oslo"));

我真的不想每次处理日期时都必须传递时区,但看起来我可能必须这样做?


如果有人曾经想知道:DateTime始终默认为UTC。 - The Onin
2个回答

10

我认为这是因为这里所写的内容: http://php.net/manual/zh/datetime.construct.php

注意:当 $time 参数是 UNIX 时间戳(例如 @946684800)或指定时区(例如 2010-01-28T15:00:00+02:00)时,$timezone 参数和当前时区都会被忽略。

在构造函数中,您可以使用UNIX时间戳设置DateTime对象的日期。

尝试使用以下方式设置DateTime对象

$date = new DateTime('2000-01-01');

谢谢,我刚刚读到关于$timezone参数的部分,应该注意到当前时区的部分。 - lshas

7

你可以始终使用继承来规避这个问题,这是更加明确的方式。

**

class myDate extends DateTime{
    public function __construct($time){
        parent::__construct($time);
        $this->setTimezone(new DateTimeZone("Europe/Oslo"));
    }
}
$str = strtotime('2015-04-12');
$md = new myDate("@".$str);
echo $md->getTimezone()->getName();

**


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接