1

Important note: My question is specifically about DateInterval. I am NOT interested in DateTime::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?

Christophe
  • 68,716
  • 7
  • 72
  • 138
Jaume Mal
  • 546
  • 5
  • 21
  • The question has been edited to explain it does not relate to DateTime::modify (which has answers) but specifically to DateInterval, please reopen. – Jaume Mal Jan 31 '20 at 17:39
  • 4
    It's the same issue. When you're creating a date without specifying the day, it uses the current day, which today is 31. There is no February 31st, so adding a month moves it to March 2nd (this year, it's usually March 3rd, I think). The way to fix it is to modify the date you create to be the first of the month, and then adding months will work as expected. – aynber Jan 31 '20 at 17:49
  • Ok, understood, thank you. – Jaume Mal Jan 31 '20 at 17:50

0 Answers0