2014-04-02 30 views
2

經與的strtotime一些意外的行爲:php strtotime +2.5小時的錯誤?

$d = '2.5';         // i.e. hours 
$t = '2014-03-20 08:30:00';     // mysql datetime 
$ut = strtotime($t);       // value: 1395297000 
$s = $d * 60 * 60;       // duration in seconds: 9000 
$plusHrs = strtotime($t.' +'.$d.' hours'); // value: 1395315000 
$plusSec = strtotime($t.' +'.$s.' seconds'); // value: 1395306000 

預期的行爲將是$ plusHrs = $ plusSec。無論輸入什麼日期,這都會發生,這意味着它不是夏令時問題。

這是一個錯誤? (PHP v5.3.14)

回答

4

不,這不是一個錯誤。 strtotime()需要relative格式的整數值。因此,您的+2.5小時將被視爲"+2 GMT",然後"+5"小時,點將被忽略。您可以將其更改爲逗號或甚至刪除 - 結果不會更改,因爲再次僅解析整數。所以,這樣的聲明將被視爲相對小時,然後加入相對於GMT的偏移:

//this is the same things: 
//and they mean set timesone to GMT+2 & add 5 hours: 
date('Y-m-d H:i:s', strtotime('now +2.5 hours')); 
date('Y-m-d H:i:s', strtotime('now +2,5 hours')); 
date('Y-m-d H:i:s', strtotime('now +2 5 hours')); 

因此,例如,+1.5 hours會做add 5 hours for time in GMT +1。這意味着,最終結果將取決於當前時區的,因爲初始時間戳將設置爲當前時區(上面示例中爲now)。

+0

嗯,這並不完全正確......把周圍的每一個線條的var_dumps,你就會明白我的意思。前3個陳述將增加5個小時,而不是7個小時。 – geoidesic

+0

那麼,這是測試,它給我相同的4行。我將檢查PHP版本 –

+0

@geoidesic是什麼增加了這一點。這不是'+7小時'(好吧,不是所有的時區)。這有點複雜。 –

0
$plusHrs = strtotime($t.' +'.$d.' hours');  
$plusSec = strtotime($t.' +'.$s.' seconds'); 

These two are different, $s = $d * 60 * 60 while $d = '2.5. 
+0

你是什麼意思「不同」?在本地,2.5 * 60 * 60秒_is與2.5小時相同 –

+0

如果您的意思是.5爲30分鐘,那是另一回事 – kimbarcelona

0

你可以用這個嘗試了幾個小時2.5

$plusHrs = strtotime($t.' + 2 hours 30 minutes');