PHP date and time processing functions in detail
Working with dates and times is a common task in web development, and PHP provides a number of powerful date and time handling functions such as strtotime
, date
and DateTimeImmutable::createFromFormat
.
These functions make it easy to convert between different time formats, perform date and time calculations, and format output.
In this article, we’ll take a closer look at the usage and advantages of these three functions.
1. strtotime function
The strtotime
function is used to convert human-readable date and time strings to Unix timestamps. It takes a datetime string as an argument and tries to parse it and convert it to a corresponding Unix timestamp. In addition to accepting the basic datetime format, it also understands various relative time expressions. Here are the arguments and roles of the strtotime
function.
strtotime(string $datetime, ?int $baseTimestamp = null): int|false
- Parameters:
string $datetime, ?int $baseTimestamp = null
. $datetime
: datetime string to be parsed.$baseTimestamp
: optional, indicates the base timestamp used to calculate the relative date.- Return value: the corresponding Unix timestamp is returned if parsing succeeds, or
false
if parsing fails.
When using the strtotime
function, you can pass in a variety of datetime strings in different formats, including absolute times (e.g. “2023-08-06”, “15:30:00”) and relative times (e.g. “tomorrow”, “next week”).
The function will try to make a reasonable date-time conversion based on the incoming string, which is convenient for time calculations and comparisons.
echo strtotime("2023-08-06 15:30:00"), PHP_EOL;
echo strtotime("tomorrow"), PHP_EOL;
echo strtotime("+1 day"), PHP_EOL;
2. date Function
The date
function is used to format a Unix timestamp into a desired date and time string. It takes a format string and a Unix timestamp as arguments and returns a formatted date-time string. The following are the arguments to the date
function and what it does.
date(string $format, ?int $timestamp = null): string
- Parameters:
string $format, ?int $timestamp = null
. $format
: datetime format string containing various formatting options to define the datetime style of the output.$timestamp
: optional parameter indicating the Unix timestamp to be formatted. Defaults to the return value of thetime()
function, which is the current Unix timestamp.- Return Value: Returns a formatted datetime string according to the specified format.
The first argument to the date
function is a date format string containing various formatting options, such as “Y” for year, “m” for month, “d” for day, “H” for hour, “i” for minute, “s” for second, and so on.
// set the default timezone to use.
date_default_timezone_set('UTC');
// Prints something like: Monday
echo date("l");
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);
// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
By combining these options, a variety of different date and time formats can be created.
3. DateTimeImmutable::createFromFormat function
The DateTimeImmutable::createFromFormat
method is object-oriented date and time processing that parses a date string into a DateTimeImmutable
object based on the specified format.
This is useful for dealing with different regional date formats or date strings that require more precise parsing.
public static DateTimeImmutable::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false
date_create_immutable_from_format(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false
The following are the parameters and roles of the DateTimeImmutable::createFromFormat
method:
- Parameters:
string $format, string $datetime, ?DateTimeZone $timezone = null
$format
: datetime format string, used to specify the format of the input datetime string.$datetime
: datetime string to be parsed.$timezone
: optional parameter, used to set the timezone of the parsedDateTimeImmutable
object. If not specified, the default isnull
, which means use the server’s timezone setting.- return value: return a
DateTimeImmutable
object if the parsing succeeds, orfalse
if the parsing fails.
When using the DateTimeImmutable::createFromFormat
method, you need to define a format string that matches the input datetime string.
$dateString = "06/08/2023";
$format = "d/m/Y";
$dateTime = DateTimeImmutable::createFromFormat($format, $dateString);
if ($dateTime instanceof DateTimeImmutable) {
echo $dateTime->format("Y-m-d"); // 2023-08-06
}
4. Summary
Date and time handling is a common but complex task in PHP. The strtotime
, date
and DateTimeImmutable::createFromFormat
functions provide us with powerful tools that make it easier to work with dates and times in different formats.
strtotime
is used to convert strings to Unix timestamps, date
is used to format timestamps into readable strings, and DateTimeImmutable::createFromFormat
allows for more precise parsing of date strings.
By becoming proficient with these functions, you will be able to better handle and manage date-time related tasks and increase the efficiency of your web development.