PHP includes a robust set of built-in date and time functions that allow you to perform a wide range of operations, such as creating time objects, setting time zones, formatting output, and calculating time intervals. These are essential tools in modern web development.
To manage packages related to time handling in PHP, it's recommended to use Composer:
composer require phpoffice/phpspreadsheet
You can also manually download the Composer installer from its official website and run the following command:
php composer.phar require phpoffice/phpspreadsheet
PHP’s DateTime class allows you to create objects that represent the current date and time:
$date = new DateTime();
Here are some common formatting methods:
Method | Description |
---|---|
$date->format('Y-m-d') | Returns the date in year-month-day format |
$date->format('H:i:s') | Returns the time in hour:minute:second format |
$date->setTimezone(new DateTimeZone('Asia/Shanghai')) | Sets the timezone to Shanghai |
You can add or subtract time intervals using the DateInterval class:
Method | Description |
---|---|
$date->add(new DateInterval('P1D')) | Adds one day |
$date->sub(new DateInterval('PT1H')) | Subtracts one hour |
PHP supports a variety of predefined formats for displaying dates and times:
Format String | Description |
---|---|
F j, Y | Full month name, day, and year (e.g., July 26, 2025) |
M j, Y g:i a | Short month name, day, year, and 12-hour time (e.g., Jul 26, 2025 3:30 pm) |
Y-m-d H:i:s | ISO 8601 standard format |
You can use the strftime() function to apply custom formats:
$formattedDate = strftime('%A, %B %e, %Y %H:%M:%S');
The following code demonstrates how to calculate the difference between two timestamps:
$startTime = new DateTime('2022-04-01 09:00:00');
$endTime = new DateTime('2022-04-01 17:00:00');
$interval = $startTime->diff($endTime);
echo $interval->format('%h:%i:%s'); // Output: 08:00:00
If you want to explore PHP’s date and time handling further, refer to the official documentation:
Mastering PHP date and time functions not only improves code quality but also enables flexible handling of user input, scheduling tasks, and more. It's a key skill every PHP developer should have.