Home  >  Article  >  Backend Development  >  Convert php numeric timestamp to date and time

Convert php numeric timestamp to date and time

WBOY
WBOYOriginal
2024-04-09 12:54:01887browse

PHP Convert numeric timestamp to date and time: Use the date() function to convert a timestamp to a date and time in a specific format. Use the gmdate() function to convert a timestamp to a date and time in Greenwich Mean Time (GMT) format. Additional format specifiers are supported, such as d (date), m (month), Y (year), H (hour), i (minute), and s (second).

Convert php numeric timestamp to date and time

Convert PHP numeric timestamp to date and time

In PHP, a numeric timestamp represents the UTC epoch (1970 The number of seconds since midnight on January 1, year). To convert a numeric timestamp to a date and time, you can use the following function:

date()

Syntax:

date(format, timestamp)

Where:

  • format: Specifies the format of the date and time
  • timestamp: The timestamp to be converted

Example:

$timestamp = 1653433200;
$date = date('Y-m-d H:i:s', $timestamp);
echo $date; // 输出:2022-05-25 12:00:00

gmdate()

Syntax:

gmdate(format, timestamp)

The gmdate() function is similar to the date() function, but it uses Greenwich Mean Time (GMT) instead of local time.

Example:

$timestamp = 1653433200;
$date = gmdate('Y-m-d H:i:s', $timestamp);
echo $date; // 输出:2022-05-25 07:00:00

Demo Example

Suppose we have a database field that stores a timestamp. To get the date and time from this field we can use the following code:

$timestamp = $row['timestamp'];
$date = date('Y-m-d H:i:s', $timestamp);
echo $date; // 输出:日期和时间

Other format specifiers

In addition to the above formats, the date() function also supports Other format specifiers, including:

  • d: Day of the month (01 to 31)
  • m: Month ( 01 to 12)
  • Y: Year (for example, 2022)
  • H: Hour in 24-hour format (00 to 23)
  • i: minutes (00 to 59)
  • s: seconds (00 to 59)

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

Statement:
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