2012-02-06 45 views
2

雖然用PHP玩,我strucked這個:PHP:奇怪DateInterval長度計算

<?php 

$FebruaryTheFirst = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-02-01 00:00:00'); 
$MarchTheSecond = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-03-01 00:00:00'); 

$interval = $FebruaryTheFirst->diff($MarchTheSecond); 

echo $interval->m.PHP_EOL; // Outputs 0. WTF? 

$FebruaryTheFirstbis = \DateTime::createFromFormat('Y-m-d', '2001-02-01'); 
$MarchTheSecondbis = \DateTime::createFromFormat('Y-m-d', '2001-03-01'); 

$interval2 = $FebruaryTheFirstbis->diff($MarchTheSecondbis); 

echo $interval2->m.PHP_EOL; // Outputs 1. WTF? 

$FebruaryTheFirstter = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-02-01 00:01:00'); 
$MarchTheSecondter = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-03-02 00:01:00'); 

$interval3 = $FebruaryTheFirstter->diff($MarchTheSecondter); 

echo $interval3->m.PHP_EOL; // Outputs 0. WTF? 

$FebruaryTheFirstfour = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-02-01 01:00:00'); 
$MarchTheSecondfour = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-03-02 01:00:00'); 

$interval4 = $FebruaryTheFirstfour->diff($MarchTheSecondfour); 

echo $interval4->m.PHP_EOL; // Outputs 1. WTF? 

問題

我應該總是讓1作爲輸出,因爲我總是之間計數月份的數字Februar,1日和3月1日。但如前所示,我也得到0 => WTF?

的信息我的PHP版本是

PHP 5.3.8 (cli) (built: Jan 12 2012 19:12:32) Copyright (c) 1997-2011 
The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend 
Technologies with Xdebug v2.1.1, Copyright (c) 2002-2011, by Derick Rethans 
+1

什麼是你的問題正是 – 2012-02-06 16:24:08

+0

@Topener:我編輯更精確。我的問題是爲什麼輸出變化,哪裏沒有。 – 2012-02-06 16:49:09

+0

我無法在5.3.6和5.4.0-rc7,1中直接複製此行爲。 – Charles 2012-02-06 16:52:50

回答

3

它看起來這是在PHP中一個已知的bug。看看bug report。至少目前來說,解決這個問題的唯一方法是使用UTC來消除當地時區問題。

例子:

// Get the current timezone. 
$originalTimezone = @date_default_timezone_get(); 

// Work in UTC. 
date_default_timezone_set('UTC'); 

// ... 
$dateStart = new DateTime('2001-02-01'); 
$dateEnd = new DateTime('2001-03-01'); 
$interval = $dateStart->diff($dateEnd); 

// Reset the timezone. 
if ($originalTimezone) { 
    date_default_timezone_set($originalTimezone); 
} 
+1

謝謝@Francois,它讓我很難過,看到2010年的一個bug仍然搞亂了PHP代碼:/ – 2012-02-06 17:22:53

+0

@ClementHerreman - 我也是。我不知道這個bug直到今天才存在,因爲它不會影響我。我希望他們儘快修復。 – 2012-02-07 00:33:37