Skip to content
Advertisement

PHP month before last

I have used date('F', strtotime('last month')) successfully to get the name of the previous month (currently December) but how to I get the month before last (currently November)?

Looking at https://www.php.net/manual/en/datetime.formats.relative.php this doesn’t appear to be a built-in feature.

Advertisement

Answer

You can use following code:

date('F',strtotime("-2 Months"));

For more details, have a look here:
https://www.php.net/manual/en/datetime.formats.php

======== EDIT =======
As @jspit mentioned, in certain days this solution will not work. For example:

echo date('F',strtotime("-2 Months", strtotime("31 January 2010")));

Instead of returning November as expected, we will get December. It is due to how strtotime calculates relative time by a string.

In order to fix this, we need the timestamp of first day of current month as a reference. This will be achieved by:

strtotime(date('Y-m-01')));

So the correct solution will be:

date('F',strtotime("-2 Months", strtotime(date('Y-m-01'))));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement