修正了添加月份时的闰年错误


Fix year leap bug when adding month php

当datetime对象具有日期'2012-01-30'时,我们有以下对象:

object(DateTime)#1233 (3) {
  ["date"]=>
  string(19) "2012-01-30 00:00:00"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(9) "ETC/GMT+3"
}

但是,当添加月份时:

$date->add(new DateInterval('P1M'));

它将产生以下对象:

object(DateTime)#1233 (3) {
  ["date"]=>
  string(19) "2012-03-01 00:00:00"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(9) "ETC/GMT+3"
}

它应该添加一个月,所以要显示的日期应该是'2012-02-28',即2012年2月,而不是2012年3月。

我该如何解决这个问题?

try this

function add($date_str, $months)
{
    $date = new DateTime($date_str);
    $start_day = $date->format('j');
    $date->modify("+{$months} month");
    $end_day = $date->format('j');
    if ($start_day != $end_day)
        $date->modify('last day of last month');
    return $date;
}
$result = add('2011-01-31', 1);  // 2011-02-28