Home > Article > Backend Development > How to query timestamp in php
PHP timestamp is a decimal number that represents the number of seconds from 0:00:00 on January 1, 1970 to the present. It is widely used in PHP for date and time calculations and data storage because it can be flexibly converted into a variety of date and time formats. This article will introduce how to perform timestamp query operations in PHP.
Getting the current timestamp in PHP is very simple, just use the time() function:
$timestamp = time(); echo $timestamp;
This The current timestamp will be output, for example: 1621738979.
In actual development, we usually need to convert timestamp to a more readable date format, for example: 2021 May 23rd.
Use the date() function to convert the timestamp to a date and time in the specified format:
$timestamp = 1621738979; $date = date("Y年m月d日 H:i:s", $timestamp); echo $date;
This will output the date and time in the following format:
2021年05月23日 09:29:39
Sometimes we need to query the date and time represented by the specified timestamp. You can use a method similar to the above:
$timestamp = 1621738979; $date = date("Y年m月d日 H:i:s", $timestamp); echo "时间戳 " . $timestamp . " 对应的日期和时间为:" . $date;
This The following content will be output:
时间戳 1621738979 对应的日期和时间为:2021年05月23日 09:29:39
In addition to the time() function mentioned in point 1, we can also use the DateTime class to Get the current date and time:
$date = new DateTime(); echo $date->format('Y年m月d日 H:i:s');
This will output the current date and time, for example: 09:29:39 on May 23, 2021.
In some cases, we need to query the timestamp within the specified time period, such as getting the start and end of a certain day End timestamp.
$day = strtotime('2021-05-23'); $startOfDay = strtotime('midnight', $day); $endOfDay = strtotime('tomorrow', $startOfDay) - 1; echo "2021年05月23日的开始时间戳为:" . $startOfDay . "<br>"; echo "2021年05月23日的结束时间戳为:" . $endOfDay . "<br>";
This will output the following:
2021年05月23日的开始时间戳为:1621737600 2021年05月23日的结束时间戳为:1621823999
In the above example, the date string is first converted to a timestamp using the strtotime() function. Then, use the 'midnight' parameter to get the start timestamp of the day, and the 'tomorrow' parameter to get the start timestamp of the next day, subtracting 1 second to get the end timestamp of the day.
Summary:
Using timestamps for date and time processing in PHP is very convenient and efficient. This article introduces how to get the current timestamp, convert the timestamp to date format, query the date and time of the specified timestamp, get the current date and time, and get the timestamp within the specified time period. I hope it will be helpful to you. .
The above is the detailed content of How to query timestamp in php. For more information, please follow other related articles on the PHP Chinese website!