PASSWORD RESET

Your destination for complete Tech news

PHP

How to get the previous month from date in PHP?

2.16K 2
< 1 min read

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.

2 Comments

  • Andrii says:

    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 🙂

    • Techradiant says:

      There was a small bug in the code, it should be date(‘Y-m-d’), instead it was date(‘Y-m’) previously.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.