首页 > 文章列表 > php将时间戳转换成日期时间格式

php将时间戳转换成日期时间格式

php 时间戳
130 2024-04-23

在 PHP 中,可以通过使用 date() 函数将时间戳转换为日期时间格式,例如 "2023-03-08 12:34:56"。该函数接受时间戳和格式字符串作为参数。例如:$formatted_date = date("Y-m-d H:i:s", $timestamp);。还可以使用 gmdate() 和 strtotime() 函数进行转换,分别用于基于 GMT 的日期时间生成和日期时间字符串到时间戳的转换。

php将时间戳转换成日期时间格式

在 PHP 中将时间戳转换为日期时间格式

简介

在 PHP 中,时间戳是一个表示自 1970 年 1 月 1 日以来的秒数的整数。有时需要将时间戳转换为人可读的日期时间格式,例如 "2023-03-08 12:34:56"。

使用 PHP 函数

PHP 提供了多个函数来进行时间戳转换:

  • date() - 将时间戳转换为指定格式的日期时间字符串。
  • gmdate() - 与 date() 类似,但生成基于格林威治标准时间 (GMT) 的日期时间字符串。
  • strtotime() - 将日期时间字符串转换为时间戳。

实战案例

假设您有一个时间戳 $timestamp,代表 2023 年 3 月 8 日 12:34:56。

使用 date()

使用 date() 函数将时间戳转换为 "Y-m-d H:i:s" 格式的日期时间字符串:

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

使用 gmdate()

使用 gmdate() 函数将时间戳转换为基于 GMT 的 "Y-m-d H:i:s" 格式的日期时间字符串:

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

使用 strtotime()

如果您有一个日期时间字符串并且需要将其转换为时间戳,可以使用 strtotime() 函数:

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