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?