将日期添加到日期时的意外结果

时间:2016-11-27 16:00:11

标签: php date

我需要添加3个月的日期,直到通过某个日期:

  $next_dt = date('Y-m-d H:i:s', strtotime('2015-12-31 00:00:00'));
  while($next_dt <= '2016-11-07 00:00:00'){
       $next_dt = date('Y-m-d H:i:s', strtotime("+3 months",strtotime($next_dt)));      
  }

此添加的结果是2017-01-01 00:00:00 虽然我期待结果是2016-12-31 00:00:00

如果我一次添加12个月,结果是正确的

$orig_dt = date('Y-m-d H:i:s', strtotime('2015-12-31 00:00:00'));
$next_dt = date('Y-m-d H:i:s', strtotime("+12 months", strtotime($orig_dt)));

但我事先无法知道需要添加多少个月

我该怎么办?

1 个答案:

答案 0 :(得分:0)

使用strtotime()和&#39; +1个月&#39;很麻烦,因为它并没有像人们期望的那样完全正常工作。

更简单的说,strtotime(&#39; + 1个月&#39;,...)似乎只需添加30天,无论月份如何。在某些月份,这是一个问题,因为并非所有月份都有30天。

我不会使用&#39; +1个月&#39;要做到这一点,我过去经常做的是每个月一个接一个,只是到了月的最后一天,再加1天。它可能不是最优雅的解决方案,但它更安全。