2017-11-11 207 views
0

我有以下代碼:碳時區功能是不正確

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

這產生完全innacturate時間戳。它似乎實際上是從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'); 

它完美。

這是怎麼發生的?我想用碳來達到這個目的,所以我不必與date_default_timezone_set混淆。

回答

0

這裏的問題是運行tz。事實上,它不會讓你的日期在給定時區的情況下解析,但它會將日期從當前時區轉換爲你給出的時區。假設你有UTCtimezoneapp.php文件(什麼是默認的),你現在做的:

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

所以你承擔的日期是UTC時區,然後你將它轉換成美國/多倫多什麼明顯不是你想要的。

你應該做的分析日期時,像這樣正在通過時區:

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