PHP StrToTime() Returns Incorrect Timestamp ‘-1 MONTH’

Posted on May 31, 2019 at 9:04 am

If you use date() with strtotime() to get the last 12 months (or the last 1 month, the last 2 months, etc) you may have noticed that when you are on the last day of the current month, i.e 31 of May, you will get repeated months, for examples:

echo date("M Y");
echo date("M Y", strtotime('-1 MONTH'));
echo date("M Y", strtotime('-2 MONTH'));
echo date("M Y", strtotime('-3 MONTH'));

The above code will incorrectly print the following months:

May 2019
May 2019
Mar 2019
Mar 2019

To fix this behavior you need to use “FIRST DAY OF -1 MONTH”, i.e:

echo date("M Y");
echo date("M Y", strtotime('FIRST DAY OF -1 MONTH'));
echo date("M Y", strtotime('FIRST DAY OF -2 MONTH'));
echo date("M Y", strtotime('FIRST DAY OF -3 MONTH'));

And it will correctly print the correct months:

May 2019
Apr 2019
Mar 2019
Feb 2019

Receive updates via email

Other Posts

Updated Posts