Carbon 时区功能不正确

Carbon timezone function is incorrect

我有以下代码:

// $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.

这里的问题是运行tz。事实上,假设给定时区,它不会让你的日期被解析,但它会将日期从当前时区转换为你提供的时区。假设您在 app.php 文件中的 UTC 中设置了 timezone(默认设置),您现在正在做的是:

$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;