Example to explain php query timestamp

PHPz
Release: 2023-03-29 10:18:17
Original
1075 people have browsed it

In development, we usually need to query and compare time. In PHP, timestamp is one of the important concepts for dealing with time issues. This article will introduce the methods and application scenarios of PHP query timestamp.

What is the timestamp?

The timestamp is the number of seconds from January 1, 1970 00:00:00 UTC to the current time. In PHP, we can use the time() function to get the timestamp of the current time.

For example:

echo time(); // 输出当前时间的时间戳
Copy after login

Output result:

1633694311
Copy after login
Copy after login
Copy after login

PHP query timestamp method

1. date() function

date () function can format a timestamp into a date and a date into a timestamp.

  1. Convert timestamp to date
echo date('Y-m-d H:i:s', time());
Copy after login

Output result:

2021-10-08 20:51:51
Copy after login
  1. Convert date to timestamp
echo strtotime('2021-10-08 20:51:51');
Copy after login

Output result:

1633694311
Copy after login
Copy after login
Copy after login

2. DateTime class

The DateTime class provides a wealth of date and time operation methods, and can also be used for timestamp queries.

$dateTime = new DateTime();
echo $dateTime->getTimestamp();
Copy after login

Output result:

1633694311
Copy after login
Copy after login
Copy after login

Application scenario

  1. Calculate the time difference between two dates
$dateTime1 = new DateTime('2021-09-30 10:00:00');
$dateTime2 = new DateTime('2021-10-08 11:00:00');
$interval = $dateTime2->diff($dateTime1);
echo $interval->format('%R%a days %H:%I:%S'); // %R 表示正负号
Copy after login

Output result:

+8 days 01:00:00
Copy after login
  1. Query the date one week ago
echo date('Y-m-d H:i:s', strtotime('-1 week'));
Copy after login

Output result:

2021-10-01 20:51:51
Copy after login
  1. Query the day of the week based on the timestamp
$timestamp = time();
echo date('l', $timestamp);
Copy after login

Output result:

Friday
Copy after login

Conclusion

Time stamp is one of the important concepts in dealing with time issues. In PHP, time can be easily queried and compared. The above introduces the commonly used methods and application scenarios for querying timestamps, which I believe will be helpful to PHP developers.

The above is the detailed content of Example to explain php query timestamp. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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