Home >Backend Development >PHP Problem >Let's talk about php timestamp conversion
PHP timestamp conversion
In PHP programming, timestamp is a very commonly used data type. The timestamp refers to the number of seconds that have elapsed at a certain time interval since 0:00:00 on January 1, 1970 (midnight UTC/GMT). In PHP, timestamps can be obtained through the time() function. As shown below:
$timestamp = time();
In practical applications, we often need to convert timestamps into specific date and time representations, or convert date and time into timestamps. This article will introduce how to implement these two conversions in PHP.
Convert timestamps into date and time representation
In PHP, you can use the date() function to convert timestamps into specific date and time representations. The basic usage of the date() function is as follows:
date(format, timestamp)
Among them, the format parameter is required and specifies the format of the date and time; the timestamp parameter is optional and specifies the timestamp to be converted, and the default is the current time.
The following are commonly used date and time formats:
Characters | Meaning |
---|---|
Y | Four-digit year |
y | Two-digit year |
m | Month (01~12) |
n | Month (1~12) |
d | Date (01~31) |
j | Date (1~31) |
w | Week (0~6) |
Hour (00~23) | |
Hours (01~12) | |
Minutes (00~59) | |
Seconds (00~59) |
$timestamp = time(); $date = date('Y-m-d H:i:s', $timestamp); echo "转换后的日期时间为:$date";The output result is as follows:
转换后的日期时间为:2021-02-05 10:30:00Convert date and time into timestampTo convert date and time into timestamp, you can use the strtotime() function. The strtotime() function is similar to the date() function and also requires a date and time format parameter. For example:
$datetime = "2021-02-05 10:30:00"; $timestamp = strtotime($datetime); echo "转换后的时间戳为:$timestamp";The output result is as follows:
转换后的时间戳为:1612495800It should be noted that the strtotime() function supports many date and time formats, including "Y-m-d H:i:s", " Y/m/d H:i:s" and so on. Choose the appropriate format according to the actual situation. SummaryThis article introduces how to convert timestamps into date-time representations and convert date-times into timestamps in PHP programming. Timestamps are very common in practical applications, and mastering these two conversion techniques is very important for processing date and time related business logic.
The above is the detailed content of Let's talk about php timestamp conversion. For more information, please follow other related articles on the PHP Chinese website!