In PHP, you can get the previous month from a date using the date()
function with the “m” and “Y” format characters. Here’s an example:
$dateString = '2023-02-25'; // The date to get the previous month from, in YYYY-MM-DD format
$prevMonth = date('Y-m-d', strtotime('-1 month', strtotime($dateString))); // Get the previous month from the date
echo $prevMonth; // Output: 2023-01-25
In this example, we first convert the date string to a Unix timestamp using the strtotime()
function. We then use the date()
function with the “Y-m” format characters to output the previous month in YYYY-MM format.
To get the previous month, we pass the date string to the strtotime()
function along with the “-1 month” argument, which subtracts one month from the date. We then pass the resulting timestamp to the date()
function to format it in the desired format.
If you need to output the previous month in a different format, you can use other format characters. The full list of format characters is available in the PHP documentation for the date()
function.
Not the best approach because this will not work as expected:
$dateString = ‘2023-03-29’;
$prevMonth = date(‘Y-m’, strtotime(‘-1 month’, strtotime($dateString)));
How to do it more correctly? I don’t know 🙂
There was a small bug in the code, it should be date(‘Y-m-d’), instead it was date(‘Y-m’) previously.