Beware of adding or subtracting a month from DateTime

Beware of adding or subtracting a month from DateTime
Photo by Waldemar Brandt / Unsplash

When subtracting a month from 31.03.2022, what should be the result? There isn't really a "right" answer, because it's kind of an invalid query without additional context. Do you want to receive the end of the previous month? Do you want to subtract the amount of days of the month?
When doing it with a DateTimeImmutable like (new \DateTimeImmutable('2022-03-31 00:00:00'))->modify('- 1 month') you end up with the 03.03.2022.

But why?

Internally PHP is just reducing the month value by one, which results in 31.02.2022, which doesn't exist. So its autocorrected and the 3 additional days are added to the last valid 28.02.2022 and therefore results in 03.03.2022.

Quite a pragmatic approach. But it will lead to unexpected results, so make sure to keep this logic in mind.