I stumbled upon this today:
If I substract 1 month and 1 day from today's date I get 2020-10-31 and if I reverse this, so I add 1 month and 1 day back to the original date then I should get todays date, but I get tomorrows date instead.
$now=DateTime::createFromFormat('Y-m-d', '2020-12-01');
$now->sub(new DateInterval('P1M1D'));
$now->add(new DateInterval('P1M1D'));
echo($now->format('Y-m-d')); \\ prints 2020-12-02
assert($now->format('Y-m-d')=='2020-12-01'); \\Fails
Does anyone have an explanation for this and how could I avoid getting the wrong date back?
Edit
- The code itself is useless as it is. This issue was caught by one of my unit tests. The test is checking how many days are between the current date and a given date minus
P1M1D
. This test got 1 instead of 0 yesterday. - I tried to use different ways to get the day like
strtotime('-1 month -1 day')
andDateTime
'smodify
method
Edit 2
I actually found this exact issue on stackoverflow (have no idea how I didn't find it yesterday)this answer answers my question in detail.