What is strtotime()
in PHP?
strtotime()
converts an English textual date/time description into a Unix timestamp (i.e., a number of seconds since January 1, 1970).
- It’s very useful when you want to manipulate or format dates easily.
Syntax:
strtotime(string $datetime, int|null $baseTimestamp = null): int|false
-
$datetime
→ The date/time text you want to parse.
-
$baseTimestamp
→ (Optional) A timestamp to base the calculation on.
-
Returns: the timestamp on success, or false
if parsing fails.
Simple Examples
Example 1: Current time
echo strtotime("now");
// Outputs: Current timestamp (e.g., 1714162812)
Example 2: Specific date
echo strtotime("15 August 2025");
// Outputs: 1755235200
Example 3: Relative dates
echo strtotime("+1 day"); // Tomorrow
echo strtotime("+1 week"); // Next week
echo strtotime("+1 month"); // Next month
echo strtotime("-2 days"); // Two days ago
Example 4: Combine with date()
echo date('Y-m-d', strtotime("+5 days"));
// Outputs: 2025-05-02 (if today is 2025-04-27)
Example 5: Using a base timestamp
$base = strtotime('2025-01-01');
echo date('Y-m-d', strtotime('+10 days', $base));
// Outputs: 2025-01-11
Common use cases:
- Add or subtract days from a date.
- Convert a string input to a date for comparison.
- Schedule events.
- Format user inputted dates.
Important Points
- If
strtotime()
cannot understand the input, it returns false
.
- Always validate the result before using it:
$timestamp = strtotime('invalid date');
if ($timestamp === false) {
echo "Invalid date!";
} else {
echo date('Y-m-d', $timestamp);
}