0
I’m having a certain problem adding months with php, had done using the Modify but as in the documentation itself already informs that of the error, then I tried other 3 functions I found and then the 3 bring me the same error, when a date starts in the days 29, 30 or 31 January, for example, in the month of February comes all to the day 28 (until ok there), but in the other months (March, April) should come for every created day (29, 30 or 31) and not always day 28.
How can I fix this?
Here is 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);
}
}
outworking
28/02/2017
28/03/2017
28/04/2017
while the expected result would be
28/02/2017
31/03/2017
30/04/2017
The point is that when you add 1 month and go to 28/02, the numeral for the day becomes 28. If you add 1 month to the day 28/02 will be 28/03; and another 1 month, 28/04, respectively. The code works as it should. Avoid modifying the instance of
$date
within its function that will possibly solve the problem.– Woss
Yes, that I realized, the problem I don’t know how to solve from there.
– Marcelo Diniz
have considered or heard of the strtotime() ? makes it easy to add and remove data.
– Neuber Oliveira