PHP 關於strtotime("- x month") bug的解決
strtotime('-x month'); 在涉及到月份修改的時候,可能不會得到預料的結果。
此為php的一個bug:
https://bugs.php.net/bug.php?id=27793
?
如:目前時間為: 2011-08-31 17:21:22
date_default_timezone_set('Asia/Shanghai');
$t = time();
print_r(array(
??? ??? ??? date('Y年m月',$t),
??? ??? ??? date('Y年m月',strtotime('- 1 month',$t)),
??? ??? ??? date('Y年m月',strtotime('- 2 month',$t)),
));
?>
上面代碼輸出:
Array
(
??? [0] => 2011年08月
??? [1] => 2011年07月
??? [2] => 2011年07月
)
而預期的結果是:
Array
(
??? [0] => 2011年08月
??? [1] => 2011年07月
??? [2] => 2011年06月
)
?
============================================
?
可以用如下方法解決:
date_default_timezone_set('Asia/Shanghai');
$first_day_of_month = date('Y-m',time()) . '-01 00:00:01';
$t = strtotime($first_day_of_month);
print_r(array(
??? ??? ??? date('Y年m月',$t),
??? ??? ??? date('Y年m月',strtotime('- 1 month',$t)),
??? ??? ??? date('Y年m月',strtotime('- 2 month',$t)),
));
?>
輸出:
Array
(
??? [0] => 2011年08月
??? [1] => 2011年07月
??? [2] => 2011年06月
)