Important note: My question is specifically about
DateInterval
. I am NOT interested inDateTime::modify()
that is proposed in some answers. This is therefore not a duplicate.
I try to add a DateInterval
of P1M
(one month) to a DateTime
object using a DateInterval
object. Unfortunately, this seems to result in two months being added.
This code (please mind the echoes):
<?php
$date = date('m-Y');
echo $date . '<br />';
$date_subonemonth = DateTime::createFromFormat('m-Y', $date);
$date_addonemonth = DateTime::createFromFormat('m-Y', $date);
echo $date_subonemonth->format('m-Y') . '<br />';
echo $date_addonemonth->format('m-Y') . '<br />';
$one_month = new DateInterval('P1M');
$date_subonemonth = $date_subonemonth->sub($one_month)->format('m-Y');
$date_addonemonth = $date_addonemonth->add($one_month)->format('m-Y');
echo $date_subonemonth . '<br />';
echo $date_addonemonth . '<br />';
?>
Outputs the following:
01-2020
01-2020
01-2020
12-2019
03-2020
The last echo should output 02-2020
instead, it output 1-2020
when I added $one_month
to it.
Why does this happen? And how can I solve this using DateInterval
?