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
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.
What should I do if the 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.