0

Why does subtracting a month from a DateTime using DateInterval sometimes produce a day in the same month and sometimes in a different month?

<?php


$dt = new DateTime('2023-05-31');
$months = 1;
$dt->sub(new DateInterval('P'.$months.'M'));;
var_dump($dt->format('Y-m-d')); // 2023-05-01 -- in the same month!!


$dt = new DateTime('2023-11-30');
$months = 1;
$dt->sub(new DateInterval('P'.$months.'M'));;
var_dump($dt->format('Y-m-d')); // 2023-10-30 -- in a different month, as expected

Tested using PHP 8.28 using https://onlinephp.io/ but I suspect the PHP version doesn't matter.

Asking:

  • Why does subtracting a DateInterval work this way? Another way of asking is "What does 'a date interval of 1 month" mean?" but I couldn't find what such a date interval is supposed to mean in the documentation for DateInterval.
  • Are there known workarounds?
Max Heiber
  • 14,346
  • 12
  • 59
  • 97
  • 2
    When you subtract a month, you get the same day in the previous month. So May 31 goes to April 31. But April only has 30 days, so that's May 1. – Barmar Jul 26 '23 at 16:56
  • _What does 'a date interval of 1 month' mean?_ - well that's the key, really. "One month" isn't a stable unit of time, it changes based on the context (generally, not just in PHP). What date would you say is one month later than January 31st? Whatever answer you choose, what date would you say is one month earlier than that? – iainn Jul 26 '23 at 17:27
  • _"Are there known workarounds?"_: Always take the first of a month. Or start using week numbers, a week always has 7 days (you only need to define what the first day of the week is). – hakre Jul 26 '23 at 17:29

0 Answers0