PHP';s DateTime默认时区


PHP's DateTime default timezone

我最近刚开始在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传递给构造函数也不起作用,因为DateTime在给定UNIX时间戳时会忽略它。(如果我将一个常规日期字符串传递给构造函数,它就会起作用)。

如果我这样做,日期会正确出现:

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

我真的不想每次约会都要经过时区,但从看起来我可能不得不这样做吗?

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

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

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

尝试使用这种方式设置DateTime对象

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

嗨,您总是可以使用继承来绕过这个问题。更明确的方式是

**

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();

**