In this article, we will see how to get the previous month’s date using PHP.
There is a built-in function called strtotime() in PHP which can be can be used to determine and retrieve the date for the previous month. By using a string representation of a date and time, the strtotime() function creates a Unix timestamp. After that, we can format the timestamp as a date using the date() function.
In the following example, we will see how to get date of previous month using php
$prevMonth = strtotime("-1 month");
$prevMonth = date("Y-m-d", $prevMonth);
Explanation:
- The strtotime() function which is present in the first line to subtract one month from the current date and time.
- The second line uses the date() function to turn the timestamp into a date in the format Y-m-d.
- The Y is the year with the century as a decimal, the m is the month with leading zeros and d is the day.
Following example shows how to get current month
To get the current month, first we need to get the current month timestamp using the time() function & use date() function to format the timestamp to “F Y“.
F is the textual representation of the month i.e. January, February etc., and Y represent the Year.
$timestamp = time();
$currentMonth = date("F Y", $timestamp);