Home  >  Article  >  Backend Development  >  Example to explain php query timestamp

Example to explain php query timestamp

PHPz
PHPzOriginal
2023-03-29 10:13:581023browse

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.

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

Output result:

2021-10-08 20:51:51
  1. Convert date to timestamp
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

  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 表示正负号

Output result:

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

Output result:

2021-10-01 20:51:51
  1. Query the day of the week based on the timestamp
$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!

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