How to Get The Previous Month From Date in PHP

How to get the previous month from date in PHP
275 Views

In this tutorial, we will explore different approaches to obtain the previous month from a given date in PHP. We will discuss both procedural and object-oriented methods, ensuring that you have a comprehensive understanding regardless of your preferred programming style.

In PHP, use the date() method with the “m” and “Y” format characters to retrieve the preceding month from a date. Here’s an example

<?php
$dateString = '2023-06-06'; // 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-05-06
?>

How to get the next month from date in PHP

<?php
$dateString = '2023-06-06'; // The date to get the next month from, in YYYY-MM-DD format
$nextMonth = date( 'Y-m-d', strtotime( '+1 month', strtotime( $dateString ) ) ); // Get the next month from the date

echo $nextMonth; // Output: 2023-07-06
?>

FAQs: People Also Ask

Q1. Can I Retrieve The Previous Month From a Specific Date in PHP?

Absolutely! PHP provides various functions and methods to manipulate dates. By using functions like date() and strtotime(), you can easily retrieve the previous month from a given date.

Q2. What Should I Do If he Current Month is January and I Want to Get The previous Month?

When the current month is January, and you want to retrieve the previous month, the year also needs to be adjusted.

Read Next:

How to Add Content After or Before The ‘Add to Cart’ Button on Single Product Page WooCommerce

Leave a comment

Your email address will not be published.