2

当 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 月。

我该如何解决这个问题?

4

1 回答 1

1

尝试这个

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
于 2015-09-09T13:29:40.100 回答