温馨提示×

PHP now函数与时间戳转换方法

PHP
小樊
81
2024-10-09 05:54:27
栏目: 编程语言

在 PHP 中,now() 函数和 strtotime() 函数都可以用于获取当前时间戳。

now() 函数返回当前的日期和时间,格式为 YYYY-MM-DD HH:mm:ss。例如:

$current_time = now();
echo $current_time; // 输出类似 "2022-01-01 12:34:56"

要将 now() 函数返回的日期时间字符串转换为时间戳,可以使用 strtotime() 函数。例如:

$date_string = "2022-01-01 12:34:56";
$timestamp = strtotime($date_string);
echo $timestamp; // 输出类似 1641027296

同样地,要将一个时间戳转换为日期时间字符串,也可以使用 date() 函数。例如:

$timestamp = 1641027296;
$date_string = date("Y-m-d H:i:s", $timestamp);
echo $date_string; // 输出类似 "2022-01-01 12:34:56"

0