Home > Article > Backend Development > How to convert PHP timestamp to time
PHP is a powerful programming language that is open source, free and widely used in web development. A timestamp is a Unix time-based timing method that represents the number of seconds that have elapsed since midnight on January 1, 1970. In PHP development, timestamps are often used, and developers need to convert timestamps into an easy-to-understand time format. This article explains how to convert timestamp to time format in PHP.
In PHP, the date() function can convert a timestamp into a specified time format. The following is an example:
$timestamp = time(); $date = date('Y-m-d H:i:s', $timestamp); echo $date;
In the above code, the time() function returns the current timestamp, and the date() function converts the timestamp into the time format of yyyy-mm-dd hh:ii:ss .
The strtotime() function can convert a string into a timestamp, or convert a timestamp into an easy-to-understand time format. The following is an example:
$timestamp = strtotime("2021-05-01 09:00:00"); $date = date('Y-m-d H:i:s', $timestamp); echo $date;
In the above code, the strtotime() function converts the string "2021-05-01 09:00:00" into a timestamp, and the date() function converts the timestamp It becomes the time format of yyyy-mm-dd hh:ii:ss.
PHP’s DateTime class can conveniently handle dates and times. The following is an example:
$timestamp = time(); $date = new DateTime(); $date->setTimestamp($timestamp); $result = $date->format('Y-m-d H:i:s'); echo $result;
In the above code, the setTimestamp() method sets the timestamp of the DateTime object, and the format() method converts the DateTime object into yyyy-mm-dd hh:ii:ss Time format.
strftime() function can format the time into a localized string and convert the timestamp into an easy-to-understand time Format. The following is an example:
$timestamp = time(); $date = strftime('%Y-%m-%d %H:%M:%S', $timestamp); echo $date;
In the above code, the strftime() function converts the timestamp into a localized string, and the output format is similar to the date() function.
Summary
In PHP development, it is often necessary to convert timestamps into an easy-to-understand time format. This article introduces four common processing methods, of which the date() function is the most commonly used. Method that can convert a timestamp into a time string in a specified format. If more complex date-time calculations or processing are required, it is recommended to use the DateTime class. When using the strftime() function, you need to pay attention to localization issues. No matter which method is used, developers need to choose the most suitable method based on the actual situation.
The above is the detailed content of How to convert PHP timestamp to time. For more information, please follow other related articles on the PHP Chinese website!