Here we introduce some neat tricks for PHP date manipulation. This time, we’ll share a little date magic using the “strtotime function.” This content will help both beginners and intermediate users deepen their understanding of PHP date operations.
Getting the Date One Month Ago in PHP
Let’s start with the basics: how to get the date one month before a given date.
For example, if we start from “2022-07-31,” the output will be “2022-07-01.” But wait a minute— is this really one month ago? Actually, this method has some pitfalls.
echo date('Y-m-d', strtotime('2022-07-31' . '-1 month'));
//Output: 2022-07-01
Accurately Getting the Last Day of the Previous Month
So, how do we get the “last day of the previous month” for a given date?
This is surprisingly tricky. For example, the last day of the month before “2022-01-31” is “2021-12-31,” but even if you use “2022-01-10,” one month earlier also outputs “2021-12-31.” Let’s take a look.
echo date('Y-m-d', strtotime('2022-01-31' . 'last day of previous month'));
//Output: 2021-12-31
echo date('Y-m-d', strtotime('2022-01-10' . 'last day of previous month'));
//Output: 2021-12-31
Getting the Last Day of the Next Month
Next, let’s see how to get the last day of the month after the specified date.
For example, using “2022-01-31” will output “2022-02-28.” This type of operation is particularly useful in accounting software or daily report management systems.
echo date('Y-m-d', strtotime('2022-01-31' . 'last day of next month' ));
//Output: 2022-02-28
If you want to get the first day of the month instead of the last,
it’s simple: just change “last” to “first.”
Practical Example: Calendar System
These techniques are very useful for systems such as calendars or booking platforms.
When a user selects a specific date, you can automatically calculate the previous month’s end and the next month’s end from that date, and show the range of available schedules.
Conclusion
The strtotime function in PHP is not just for manipulating dates— it’s a powerful tool for enhancing program flexibility and improving user experience. By mastering the techniques introduced in this article, you’ll sharpen your PHP skills even further.
*If you reuse these techniques, please do so at your own risk.