I'm having a problem adding months to php, I had done using modify but as in own documentation already informs that of the error, hence I tried 3 other functions that I found and hence the 3 and I bring the same error, when a date starts on days 29, 30 or 31 January, for example, in February comes all to the (28, 30 or 31) and not always on the 28th.
How can I resolve this?
Here's an example with one of these functions:
$date=new DateTime();
$date->setDate(2017,1,31);
addMonths($date, 1);
echo $date->format('d/m/Y');
echo "<br>";
addMonths($date, 1);
echo $date->format('d/m/Y');
echo "<br>";
addMonths($date, 1);
echo $date->format('d/m/Y');
function addMonths($date,$months)
{
$init=clone $date;
$modifier=$months.' months';
$back_modifier =-$months.' months';
$date->modify($modifier);
$back_to_init= clone $date;
$back_to_init->modify($back_modifier);
while($init->format('m')!=$back_to_init->format('m')){
$date->modify('-1 day') ;
$back_to_init= clone $date;
$back_to_init->modify($back_modifier);
}
}
result
28/02/2017
28/03/2017
28/04/2017
while the expected result would be
28/02/2017
31/03/2017
30/04/2017