strtotime('-x month')的bug

sanlanlan 2017-5-6 标签: PHP 浏览:2079 评论:0

 对于strtotime('-x month'); 在涉及到月份修改的时候,可能不会得到预料的结果。


如:当前时间为: 2015-08-31
<?php

$t = time();
print_r(array(
            date('Y年n月',$t),
            date('Y年n月',strtotime('- 1 month',$t)),
            date('Y年n月',strtotime('- 2 month',$t)),
));
?>
上面代码输出:
Array
(
    [0] => 2015年8月
    [1] => 2015年7月
    [2] => 2015年7月
)
而预期的结果是:
Array
(
    [0] => 2015年8月
    [1] => 2015年7月
    [2] => 2015年6月
)

 所以,在遇到strtotime('-x month')这样的情况要特别注意:

============================================
 
可以用如下方法解决:
如:当前时间为: 2015-08-31

$t = time();

//把时间都置为每月的1号,这样时间上加,减一个月就不会错了
$t = date('Y-m',$t).'-01';

  $t = strtotime('-1 month', $t);

本文相关标签: php strtotime

发表评论: