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

How to use PHP's datetime functions?

WBOY
Release: 2024-04-19 10:42:01
Original
1012 people have browsed it

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
Copy after login

Manual download

Download Composer from [PHP official website](https://getcomposer.org/download/), then run:

php composer.phar require phpoffice/phpspreadsheet
Copy after login

Usage

Create DateTime Object

$date = new DateTime();
Copy after login

Get date and time information

MethodDescription
$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
MethodDescription
$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');
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template