Current Location: Home> Latest Articles> Comprehensive Guide to PHP Date and Time Functions: Creation, Formatting, and Interval Calculation

Comprehensive Guide to PHP Date and Time Functions: Creation, Formatting, and Interval Calculation

M66 2025-07-26

Understanding PHP Date and Time Functions

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.

Installing Composer

To manage packages related to time handling in PHP, it's recommended to use Composer:

composer require phpoffice/phpspreadsheet

Manual Composer Installation

You can also manually download the Composer installer from its official website and run the following command:

php composer.phar require phpoffice/phpspreadsheet

Creating a DateTime Object

PHP’s DateTime class allows you to create objects that represent the current date and time:

$date = new DateTime();

Getting Date and Time Information

Here are some common formatting methods:

MethodDescription
$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

Modifying Date and Time

You can add or subtract time intervals using the DateInterval class:

MethodDescription
$date->add(new DateInterval('P1D'))Adds one day
$date->sub(new DateInterval('PT1H'))Subtracts one hour

Formatting Date and Time

PHP supports a variety of predefined formats for displaying dates and times:

Format StringDescription
F j, YFull month name, day, and year (e.g., July 26, 2025)
M j, Y g:i aShort month name, day, year, and 12-hour time (e.g., Jul 26, 2025 3:30 pm)
Y-m-d H:i:sISO 8601 standard format

Custom Date Formatting

You can use the strftime() function to apply custom formats:

$formattedDate = strftime('%A, %B %e, %Y %H:%M:%S');

Practical Example: Calculating Time Difference

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

Recommended Documentation

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.