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:

JavaScript

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:

JavaScript

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:

JavaScript

So the correct solution will be:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement