php convert timestamp to date time format

WBOY
Release: 2024-04-09 16:36:01
Original
629 people have browsed it

In PHP, the timestamp can be converted to date time format by using the date() function, such as "2023-03-08 12:34:56". This function accepts a timestamp and a format string as parameters. For example: $formatted_date = date("Y-m-d H:i:s", $timestamp);. Conversions can also be performed using the gmdate() and strtotime() functions, for GMT-based datetime generation and datetime string to timestamp conversion respectively.

php convert timestamp to date time format

Convert timestamp to datetime format in PHP

Introduction

In PHP, a timestamp is an integer representing the number of seconds since January 1, 1970. Sometimes it is necessary to convert the timestamp into a human-readable date-time format, such as "2023-03-08 12:34:56".

Using PHP functions

PHP provides multiple functions for timestamp conversion:

  • date() - Convert the timestamp to a datetime string in the specified format.
  • gmdate() - Similar to date(), but generates a date-time string based on Greenwich Mean Time (GMT).
  • strtotime() - Converts a datetime string to a timestamp.

Practical case

Suppose you have a timestamp $timestamp, representing 12:34:56 on March 8, 2023 .

Use date()

Use the date() function to convert the timestamp to "Y-m-d H:i: s" format date and time string:

$formatted_date = date("Y-m-d H:i:s", $timestamp);
echo $formatted_date; // 输出: 2023-03-08 12:34:56
Copy after login

Use gmdate()

Use gmdate() function to Convert the timestamp to a date-time string in GMT-based "Y-m-d H:i:s" format:

$formatted_date = gmdate("Y-m-d H:i:s", $timestamp);
echo $formatted_date; // 输出: 2023-03-08 04:34:56
Copy after login

Use strtotime()

If you have a datetime string and need to convert it to a timestamp, you can use the strtotime() function:

$timestamp = strtotime("2023-03-08 12:34:56");
echo $timestamp; // 输出: 1678291696
Copy after login

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

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!