PHP provides powerful date and time functions for manipulating and formatting date and time, including the following functions: creating a DateTime object and obtaining date and time information, setting the time zone, and manipulating date and time (such as adding a day or subtracting an hour). Predefined formatting strings or custom formatting to format datetimes to calculate time differences (such as calculating hours, minutes, and seconds between two dates)
How to use PHP's date and time functions
PHP provides a series of powerful date and time functions that can be used to operate and format dates and times.
Installation
Use Composer package manager
composer require phpoffice/phpspreadsheet
Manual download
Download Composer from [PHP official website](https://getcomposer.org/download/), then run:
php composer.phar require phpoffice/phpspreadsheet
Usage
Create DateTime Object
$date = new DateTime();
Get date and time information
Method | Description |
---|---|
$date->format('Y-m-d') | ISO 8601 date format |
$date->format('H:i:s') | ISO 8601 time format |
$date->setTimezone(new DateTimeZone('Asia/Shanghai')) | Set time zone |
Manipulate date and time
Method | Description |
---|---|
$date- >add(new DateInterval('P1D')) | Add a day |
##$date->sub(new DateInterval('PT1H '))
| Subtract one hour
Format date and time
provided by PHP There are several predefined format strings:Description | |
---|---|
F j, Y
| Day of the week, month, year|
M j, Y g:i a
| Month, day, year, hour, minute, am/pm|
Y-m-d H:i:s
| ISO 8601 format
Custom formatting
You can use thestrftime() function to customize the format Transformation:
$formattedDate = strftime('%A, %B %e, %Y %H:%M:%S');
Practical case: Calculate time difference
$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'); // 输出:08:00:00
More resources
The above is the detailed content of How to use PHP's datetime functions?. For more information, please follow other related articles on the PHP Chinese website!