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(); // 输出当前时间的时间戳
Output result:
1633694311
PHP query timestamp method
1. date() function
date () function can format a timestamp into a date and a date into a timestamp.
echo date('Y-m-d H:i:s', time());
Output result:
2021-10-08 20:51:51
echo strtotime('2021-10-08 20:51:51');
Output result:
1633694311
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();
Output result:
1633694311
Application scenario
$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 表示正负号
Output result:
+8 days 01:00:00
echo date('Y-m-d H:i:s', strtotime('-1 week'));
Output result:
2021-10-01 20:51:51
$timestamp = time(); echo date('l', $timestamp);
Output result:
Friday
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!