Convert English Datetime to Unix Timestamp in PHP
This article demonstrates how to convert English textual datetime
descriptions into Unix timestamps using PHP. You will learn how to use
the built-in strtotime() function and the object-oriented
DateTime class to parse relative and absolute English date
phrases into a standard Unix epoch integer.
Using the strtotime()
Function
The easiest and most common way to convert English text into a Unix
timestamp in PHP is by using the strtotime() function. This
function parses almost any English textual datetime description into a
Unix timestamp (the number of seconds since January 1 1970 00:00:00
UTC).
The syntax is straightforward:
strtotime(string $datetime, ?int $baseTimestamp = null): int|falseExamples of Common English Phrases
PHP can understand a wide variety of relative and absolute time formats. Here are some of the most common formats:
// Relative times
$now = strtotime("now");
$tomorrow = strtotime("tomorrow");
$yesterday = strtotime("yesterday");
$nextWeek = strtotime("+1 week");
$nextThursday = strtotime("next Thursday");
$lastMonday = strtotime("last Monday");
// Complex relative times
$twoMonthsAgo = strtotime("-2 months");
$endOfNextMonth = strtotime("last day of next month");
// Absolute times in English formats
$specificDate = strtotime("10 September 2000");
$specificDateTime = strtotime("next Monday 3:00pm");If the parsing fails (for example, if the text is not a valid date
description), strtotime() will return
false.
Using the
DateTime Class (Object-Oriented Approach)
For a more modern, object-oriented approach, you can use PHP’s
DateTime class. This method is often preferred in modern
PHP development because it integrates better with OOP codebases and
makes timezone handling easier.
To get a Unix timestamp using the DateTime class, pass
the English string to the constructor and call the
getTimestamp() method:
try {
$date = new DateTime("next Tuesday");
$timestamp = $date->getTimestamp();
echo $timestamp;
} catch (Exception $e) {
echo "Invalid date format: " . $e->getMessage();
}Handling Timezones
By default, both strtotime() and the
DateTime class interpret English textual dates based on the
default timezone set in your PHP configuration (php.ini) or
defined via date_default_timezone_set().
If you need to parse a textual date relative to a specific timezone,
you can pass a DateTimeZone object to the
DateTime constructor:
$timezone = new DateTimeZone("America/New_York");
$date = new DateTime("next Monday 12:00pm", $timezone);
$timestamp = $date->getTimestamp(); // Returns the correct UTC Unix timestamp