What can go wrong when adding months with a DateInterval and DateTime::add?

前端 未结 2 844
灰色年华
灰色年华 2020-12-07 02:51

I failed to find a proper solution to this issue. As you see in Example #3 in the PHP documentation, they state that one must beware when adding months using the DateInterva

2条回答
  •  时光取名叫无心
    2020-12-07 03:51

    If your goal is to strictly increment by user-friendly months (thus, 3 months from January 21st should be April 21st), with the exception that shorter membership months get shortened (thus, 1 month from January 31st is February 28th/29th), then you only need to go back a few days if you crossed over into the next month:

    function addMonths($date,$months) {
      $orig_day = $date->format("d");
      $date->modify("+".$months." months");
      while ($date->format("d")<$orig_day && $date->format("d")<5)
        $date->modify("-1 day");
    }
    
    $d = new DateTime("2000-01-31");
    addMonths($d,1);
    echo $d->format("Y-m-d"); // 2000-02-29
    

提交回复
热议问题