Home  >  Article  >  Backend Development  >  How to use PHP's datetime functions?

How to use PHP's datetime functions?

WBOY
WBOYOriginal
2024-04-19 10:42:01888browse

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)

如何使用 PHP 的日期时间函数?

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

Subtract one hour
Method Description
$date- >add(new DateInterval('P1D')) Add a day
##$date->sub(new DateInterval('PT1H '))

Format date and time

provided by PHP There are several predefined format strings:

Format stringDescriptionDay of the week, month, yearMonth, day, year, hour, minute, am/pmISO 8601 format
F j, Y
M j, Y g:i a
Y-m-d H:i:s

Custom formatting

You can use the

strftime() 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

    [PHP Date Time Function ](https://www.php.net/manual/en/book.datetime.php)
  • [Straff formatting](https://www.php.net/manual/en/ function.strftime.php)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn