2

I'm ussing a function which I found here to add months to a date considering that some months have less days than others.

    function addMonths($date_str, $months){
        $date = new DateTime($date_str);
        $start_day = $date->format('j');
 var_dump($date->format('Y-m-d'));
        $date->modify("+{$months} month");
        $end_day = $date->format('j');
        var_dump($date->format('Y-m-d'));
        if ($start_day != $end_day)
            $date->modify('last day of last month');
        var_dump($date->format('Y-m-d'));die();
        return $date->format('Y-m-d');
    }

Since the function is not working as expected I dumped some variables to see what's going on. Let's try the following:

addMonths('2012-05-31',1)

And I'm getting the following wrong output:

string(10) "2012-05-31" string(10) "2012-07-01" string(10) "2012-05-31"

As you can see when I add a month to input date I get "2012-07-01" but then the conditional is met and I should get the last day of June which is the previous month of July and not May. I don't know what's happening, can you help me?

Community
  • 1
  • 1
Jorge Zapata
  • 2,316
  • 1
  • 30
  • 57

3 Answers3

2

PHP had a bug with DateTime relative formats until PHP 5.2.17

Try this instead:

<?php
function addMonths($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');
  }

  return $date->format('Y-m-d');
}

echo addMonths('2012-05-31', 1);

I don't have such an old version of PHP here but I think it can handle last day in this version.

For me it returns:

2012-06-30
dan-lee
  • 14,365
  • 5
  • 52
  • 77
  • Great it also works for my version, however I will update my php version since this doesn't work for leap years. Thanks – Jorge Zapata May 02 '12 at 17:55
  • Sure no problem. And yes, I *highly* recommend to update your PHP version! – dan-lee May 02 '12 at 17:56
  • If you read the bug report it actually isn't a bug. I don't believe all of the relative time formats work prior to 5.3. http://php.net/manual/en/datetime.formats.relative.php – aknosis Mar 19 '13 at 16:36
0

I copy/pasted your code, and following is my output on PHP 5.3.3:

string(10) "2012-05-31"
string(10) "2012-07-01"
string(10) "2012-06-30"
FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107
0
    function add_month($format , $date , $months_to_add ){
        return date($format, strtotime("$date +$months_to_add month"));
}

I am using this. You can try this one.