2014-03-28 72 views
0
$months = array(); 
$first = strtotime("first day this month"); 
for ($i = 1; $i <= 6; $i++) { 
    array_push($months, date('F', strtotime("-$i month", $first))); 
} 
var_dump($months); 

今天運行時,此代碼不能正常工作(3月份)PHP日期月未正確計算

輸出:

array(6) { 
    [0]=> 
    string(5) "March" 
    [1]=> 
    string(7) "January" 
    [2]=> 
    string(8) "December" 
    [3]=> 
    string(8) "November" 
    [4]=> 
    string(7) "October" 
    [5]=> 
    string(9) "September" 
} 

哪裏是2月?

+0

可能重複[PHP DateTime ::修改加入和減去幾個月](http://stackoverflow.com/questions/3602405/php-datetimemodify-adding-and-subtracting-months) –

+0

我沒有使用DateTime也沒有使用DateTime我正在使用本月的最後一天嗎? – morissette

+0

該答案解釋了您的問題中的所有內容 –

回答

0

更改您的代碼到這個,看看到底發生了什麼:

$months = array(); 
$first = strtotime("first day this month"); 
echo date('d-F-Y', $first); 
for ($i = 1; $i <= 6; $i++) { 
    array_push($months, date('d-F-Y', strtotime("-$i month", $first))); 
} 
var_dump($months); 

你會看到你的$first日期是不正確的。它設置在29-March-2014。爲什麼二月不在那裏?因爲它只有28天:)

解決方案是:$first = strtotime("first day of this month");其中輸出01-March-2014