What are the methods to convert PHP timestamp to date format?

WBOY
Release: 2024-03-12 18:08:01
Original
482 people have browsed it

What are the methods to convert PHP timestamp to date format?

PHP timestamp refers to the number of seconds calculated from January 1, 1970 00:00:00 (Greenwich Mean Time), which is a very common way of expressing time. There are many ways to convert timestamp to date format in PHP. Here are some commonly used methods, along with specific code examples.

Method 1: Use the date() function

The date() function in PHP can format the timestamp into the specified date format. The following is a basic example:

$timestamp = time();
$date = date("Y-m-d H:i:s", $timestamp);
echo $date;
Copy after login

In the above code, the time() function is used to obtain the timestamp of the current time, and then uses the date() function to convert the timestamp into year-month-day time: Minutes:seconds format. After running the code, the date format of the current time will be output.

Method 2: Use the DateTime class

The DateTime class in PHP provides a more flexible date processing method. The following is a sample code:

$timestamp = time();
$date = new DateTime();
$date->setTimestamp($timestamp);
echo $date->format('Y-m-d H:i:s');
Copy after login

In the above code, we first create a DateTime object, then use the setTimestamp() method to pass in the timestamp, and finally use the format() method to specify the output date format.

Method 3: Use the strtotime() function

The strtotime() function in PHP can parse the string into a timestamp, and combined with the date() function can realize the time Conversion of stamp to date format. The following is an example:

$timestamp = time();
$date = date("Y-m-d H:i:s", strtotime('@' . $timestamp));
echo $date;
Copy after login

In the above code, by passing in the @ symbol and timestamp in the strtotime() function, the timestamp can be directly formatted into date format.

Through the above method, we can easily convert PHP timestamp to date format. According to the specific needs and usage scenarios, choose the appropriate method to convert timestamp and date formats.

The above is the detailed content of What are the methods to convert PHP timestamp to date format?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template