碳时区功能不正确

时间:2017-11-11 08:13:55

标签: php laravel date php-carbon

我有以下代码:

// $this->date_from = '11/01/2017';
// $this->date_to = '11/30/2017';

$this->where_date_from = Carbon::parse($this->date_from)->tz('America/Toronto')->startOfDay()->timestamp;
$this->where_date_to = Carbon::parse($this->date_to)->tz('America/Toronto')->endOfDay()->timestamp;

这会产生完全无效的时间戳。它似乎实际上减去了UTC的偏移量的两倍。

但是,当我使用以下内容时:

date_default_timezone_set('America/Toronto');
$this->where_date_from = strtotime($this->date_from.' 00:00:00');
$this->where_date_to = strtotime($this->date_to.' 23:59:59');

效果很好。

为什么会这样?我想使用Carbon来实现这一点,所以我不必使用date_default_timezone_set

1 个答案:

答案 0 :(得分:0)

此处的问题是tz正在运行。事实上,如果给定时区,它将不会使您的日期被解析,但它会将日期从当前时区转换为您给出的时区。假设您在timezone文件中UTC设置了app.php(默认值是什么),您现在正在做的事情:

$this->where_date_from = Carbon::parse($this->date_from, 'UTC')->tz('America/Toronto')->startOfDay()->timestamp;

因此,您假设日期是UTC时区,然后您将其转换为America / Toronto,这显然不是您想要的。

你应该做的是在解析日期时传递时区,如下所示:

$this->where_date_from = Carbon::parse($this->date_from, 'America/Toronto')->startOfDay()->timestamp;
$this->where_date_to = Carbon::parse($this->date_to, 'America/Toronto')->endOfDay()->timestamp;
相关问题