Working with Relative Dates in PHP — Understanding strtotime("12 days ago")
Working with dates is a common need in PHP development, especially when you need to manipulate or compare them based on user input or system events. One of the most convenient ways PHP offers to handle relative date and time calculations is the strtotime()
function.
Let's break down this simple yet powerful code snippet:
<?php
echo (date("Y-m-d", strtotime("12 days ago")));
What Does It Do?
strtotime("12 days ago")
parses the human-readable string "12 days ago" into a Unix timestamp.date("Y-m-d", ...)
formats that timestamp into aYYYY-MM-DD
string, which is a common standard format for storing and displaying dates.
Why Is This Useful?
This approach is extremely handy when you need to:
- Calculate a date range, for example: fetching records created in the last 12 days.
- Create filters for daily/weekly reports.
- Manage expiration dates or scheduled tasks.
Instead of manually calculating timestamps or subtracting seconds, strtotime()
simplifies the process using plain English expressions.
Other Relative Strings You Can Use
PHP supports a variety of relative date formats in strtotime()
:
"yesterday"
"next Monday"
"last Friday"
"+3 weeks"
"-2 months"
"first day of last month"
Each of these can be parsed naturally, making your code both powerful and readable.
Timezones Consideration
If your application depends on a specific timezone (especially in multi-region apps), make sure you set the timezone properly using:
date_default_timezone_set('Asia/Jakarta');
Otherwise, PHP might use the default system timezone, which could lead to unexpected results.
When to Be Careful
- The result of
strtotime()
depends on the validity and clarity of the string. If PHP can't understand the string, it will returnfalse
.
Always check the result before formatting:
$timestamp = strtotime("12 days ago");
if ($timestamp !== false) {
echo date("Y-m-d", $timestamp);
} else {
echo "Invalid date expression.";
}
Finally
Using strtotime("12 days ago")
is a concise and expressive way to calculate past dates in PHP. It helps keep your code clean, readable, and flexible. Just make sure to handle edge cases like invalid input and timezone differences to ensure consistent results across environments.
Comments ()