This is an easy function to add or remove months from a date in PHP.
There is a limitation, you can only subtract up to 999 years, but you can change that by increasing the 12000 number in the code, to whatever you want to.
function add_month($strbegin, $count)
{
$begin = new DateTime($strbegin . ” 00:00:00.0″);
$end = clone $begin;
if ($count > 0 )
{
$end->modify(“+$count month”);
while (abs(($begin->format(‘m’)+($count))%12) != $end->format(‘m’)%12)
{
$end->modify(‘-1 day’);
}
}
else
{
$end->modify(“$count month”);
while (abs(($begin->format(‘m’)+12000+($count))%12) != $end->format(‘m’)%12)
{
$end->modify(‘-1 day’);
}
}
return $end;
}
examples of use:
echo add_month( ‘2016-01-31’, 1 )->format(‘Y-m-d’); // 2016-02-29
echo add_month( ‘2016-01-31’, -47 )->format(‘Y-m-d’); //2012-02-29