How to Use the PHP strtotime Function
The strtotime() function is one of the most versatile
and widely used date-handling functions in PHP. This article provides a
clear overview of the purpose of strtotime(), explaining
how it converts English textual datetime descriptions into Unix
timestamps, and demonstrates how to use it for date formatting,
comparisons, and relative date arithmetic in your web applications.
What is the Purpose of strtotime()?
The primary purpose of the strtotime() function is to
parse an English textual date or time description and convert it into a
Unix timestamp. A Unix timestamp is an integer representing the total
number of seconds that have elapsed since January 1, 1970, at 00:00:00
UTC.
By converting human-readable dates into timestamps, PHP allows
developers to easily perform mathematical calculations on dates, compare
different dates, and reformat dates into various structures using the
date() function.
Basic Syntax
The syntax for the function is:
strtotime(string $datetime, ?int $baseTimestamp = null): int|false$datetime: The date/time string to be parsed. This string must conform to recognized date and time formats.$baseTimestamp: An optional parameter representing the timestamp used as the base for calculating relative dates. If omitted, the default is the current time.- Return Value: Returns the Unix timestamp integer on
success, or
falseif the string cannot be parsed.
Common Use Cases
1. Converting Standard Dates to Timestamps
You can pass a standard date string into strtotime() to
convert it into a timestamp, which can then be formatted using the
date() function.
$timestamp = strtotime("2025-12-25");
echo date("F j, Y", $timestamp); // Outputs: December 25, 20252. Relative Date Arithmetic
One of the most powerful features of strtotime() is its
ability to understand relative English phrasing. You can easily
calculate dates in the past or future.
echo date("Y-m-d", strtotime("tomorrow")); // Tomorrow's date
echo date("Y-m-d", strtotime("+1 week")); // One week from now
echo date("Y-m-d", strtotime("-3 months")); // Three months ago
echo date("Y-m-d", strtotime("next Monday")); // Next Monday's date
echo date("Y-m-d", strtotime("last day of next month")); // Last day of next month3. Comparing Two Dates
Because strtotime() converts dates into integers,
comparing two dates becomes a simple mathematical comparison.
$date1 = strtotime("2025-05-01");
$date2 = strtotime("2025-06-01");
if ($date1 < $date2) {
echo "May 1st comes before June 1st.";
}Important Considerations
- Time Zones:
strtotime()relies on the default time zone set in your PHP configuration (php.ini) or defined in your script usingdate_default_timezone_set(). - Ambiguous Formats: Dates separated by slashes
(
/) are usually assumed to be in American format (MM/DD/YY), whereas dates separated by dashes (-) or dots (.) are assumed to be in European format (DD-MM-YYorYY-MM-DD). To avoid errors, it is best to use the standard ISO 8601 format (YYYY-MM-DD).