[英]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!
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.