time()
Introduction
PHP provides a robust set of date and time functions that are essential for handling temporal data efficiently. This guide covers the most commonly used functions, their syntax, and practical usage. Note that PHP relies on the server's default timezone for functions like date() and time(). You can set it explicitly using date_default_timezone_set('UTC');.
PHP Date Function
The date() function formats a timestamp into a readable string. It accepts two parameters: format (required) and timestamp (optional, defaults to current time). The format string uses specific characters to represent date components.
Example of date() function in PHP
<?php
echo date("Y-m-d"); // outputs something like "2023-03-03"In this example, Y, m, and d represent the four-digit year, two-digit month, and two-digit day, respectively. The format string supports many other characters for hours, minutes, seconds, and more.
PHP Time Function
The time() function returns the current Unix timestamp, which counts the number of seconds since January 1, 1970, 00:00:00 UTC.
How to use PHP time() function?
<?php
echo time(); // outputs something like "1646357879"The returned integer can be passed directly to date() or other temporal functions for further processing.
PHP strtotime Function
The strtotime() function parses an English textual datetime description into a Unix timestamp. It accepts a single string argument.
PHP strtotime Function example
<?php
echo strtotime("2023-03-03 12:00:00"); // outputs something like "1646378400"This converts the specified date and time string into its corresponding Unix timestamp value.
PHP DateInterval Class
The DateInterval class represents a duration between two dates or times. Modern PHP development typically uses DateTimeImmutable to calculate intervals, as it avoids mutating the original date object.
The PHP DateInterval class example
<?php
$date1 = new DateTimeImmutable('2023-03-03');
$date2 = new DateTimeImmutable('2023-03-10');
$interval = $date1->diff($date2);
echo $interval->format('%R%a days'); // outputs "+7 days"This calculates the difference between two dates. The %R%a format specifier outputs the sign (+ or -) followed by the total number of days.
PHP Timezone Functions
PHP handles time zones through the DateTimeZone class and related methods. These allow conversion between zones and display of UTC offsets.
Example of PHP timezone functions
<?php
$dateTime = new DateTimeImmutable('2023-03-03 12:00:00', new DateTimeZone('America/New_York'));
echo $dateTime->format('Y-m-d H:i:s T'); // outputs "2023-03-03 12:00:00 EST"This outputs the date and time in the specified zone, along with its abbreviation (e.g., EST).
Conclusion
Mastering PHP's date and time functions enables developers to handle temporal data accurately across different environments and time zones.
Practice
What are the functionalities of the 'date()' function in PHP?