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?