PHP的DateTime默认时区

lsh*_*has 2 php timezone datetime

我刚刚开始在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);
Run Code Online (Sandbox Code Playgroud)

这是我得到的回应:

{
  "TZ":"+00:00",
  "OTZ":"Europe\/Oslo",
  "Date":"2015-04-11"
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

我不想在每次处理约会时都要通过时区,但是从我看来我可能需要的时间来看?

Yas*_*lev 8

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

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

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

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

$date = new DateTime('2000-01-01');
Run Code Online (Sandbox Code Playgroud)


vol*_*inc 5

嗨,你总是可以使用继承只是为了绕过问题.这是更明确的方式

**

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();
Run Code Online (Sandbox Code Playgroud)

**