How to Use strtotime in PHP: Syntax and Examples
Use
strtotime in PHP to convert a human-readable date/time string into a Unix timestamp (an integer). It accepts strings like "now", "+1 day", or "2024-06-01" and returns the timestamp or false if the input is invalid.Syntax
The strtotime function takes a date/time string and an optional base timestamp to calculate the Unix timestamp.
- string $datetime: The date/time text to parse.
- int|null $baseTimestamp: Optional. The timestamp to use as a base for relative calculations. Defaults to current time.
- Returns: An integer Unix timestamp or
falseon failure.
php
int|false strtotime ( string $datetime , int $baseTimestamp = time() )
Example
This example shows how to convert a date string and a relative time string into Unix timestamps and then format them back to readable dates.
php
<?php // Convert a specific date string to timestamp $timestamp1 = strtotime('2024-06-01'); // Convert a relative time string to timestamp $timestamp2 = strtotime('+1 week'); // Format timestamps back to readable date echo date('Y-m-d', $timestamp1) . "\n"; echo date('Y-m-d', $timestamp2) . "\n"; ?>
Output
2024-06-01
2024-06-07
Common Pitfalls
Common mistakes include passing invalid date strings, which cause strtotime to return false. Also, beware that relative strings are calculated from the current time by default, which can lead to unexpected results if you don't specify a base timestamp.
Always check the return value before using it.
php
<?php // Wrong: invalid date string returns false $wrong = strtotime('not a date'); if ($wrong === false) { echo "Invalid date string detected.\n"; } // Right: check before using $date = 'next Monday'; $time = strtotime($date); if ($time !== false) { echo date('Y-m-d', $time) . "\n"; } else { echo "Failed to parse date.\n"; } ?>
Output
Invalid date string detected.
2024-06-03
Quick Reference
| Input Examples | Description |
|---|---|
| now | Current timestamp |
| +1 day | One day from now |
| -2 weeks | Two weeks ago |
| 2024-06-01 | Specific date |
| next Monday | Next Monday from today |
| last Friday | Previous Friday |
Key Takeaways
Use strtotime to convert readable date/time strings into Unix timestamps.
Always check if strtotime returns false to handle invalid inputs.
Relative date strings calculate from current time unless a base timestamp is given.
Format timestamps back to readable dates using date() function.
Common inputs include 'now', '+1 day', specific dates, and relative terms like 'next Monday'.