时区问题:PHP DateTime返回错误的日期


Trouble with timezones: PHP DateTime returning wrong date

php的DateTime没有做我希望它做的事情....

class Time_model extends CI_model
{
    public $time_zone;
    public $tz;
    public $dt;
    public function __construct()
    {
        date_default_timezone_set('UTC');
        $this->time_zone = 'Pacific/Auckland';
        $this->tz = new DateTimeZone($this->time_zone);
        $this->dt = new DateTime('now', $this->tz);
    }
    /**
     * dates
     */
    public function getDate()
    {
        $this->dt->getTimezone(); // <--- shows that the timezone is auckland where it is the 02/10/2016 
        return $this->dt->format('Y-m-d'); // <--- yet returns the 01/10/2016! 
    }
}

在奥克兰,今天是星期天,然而即使我显式地更改了时区,也没有任何变化,它仍然显示为星期六。

如何让DateTime更改日期以匹配时区?

此外,如果将新的DateTimeZone对象传递给DateTime对象完全没有任何作用,那么首先传递它的意义是什么?这真的让我很困扰,因为我知道我完全搞错了!

当您创建DateTime的第二个参数是第一个参数的DateTimeZone时,当您要更改DateTime的时区时,您需要在使用setTimezone方法之后更改。

class Time_model extends CI_model
{
    public $time_zone;
    public $tz;
    public $dt;
    public function __construct()
    {
        $this->time_zone = 'Pacific/Auckland';
        $this->tz = new DateTimeZone($this->time_zone);
        $this->dt = new DateTime('now', new DateTimeZone("UTC"));
        $this->dt->setTimezone($this->tz);
    }
    /**
     * dates
     */
    public function getDate()
    {
        $this->dt->getTimezone(); // <--- shows that the timezone is auckland where it is the 02/10/2016 
        return $this->dt->format('Y-m-d'); // <--- yet returns the 01/10/2016! 
    }
}