PHP 时间戳相关函数

在编程中,时间戳是一个常用的概念。它表示自 Unix 元年(1970年1月1日 00:00:00 GMT)起到现在的秒数。在 PHP 中,有多个函数可以处理和操作时间戳。本文将详细介绍这些函数。

time() 函数

time() 是一个基础但非常重要的函数,它返回当前的 Unix 时间戳。例如:

$current_timestamp = time();
echo $current_timestamp; // 输出类似于: 1577836800

mktime() 函数

mktime() 函数返回一个日期的 Unix 时间戳。它需要提供年、月、日、小时、分钟、秒等参数。例如:

$timestamp = mktime(0, 0, 0, 12, 31, 2019);
echo $timestamp; // 输出: 1577836800,这是 2019年12月31日 00:00:00 的时间戳

date() 函数

date() 函数将一个 Unix 时间戳格式化为可读的日期和时间字符串。例如:

$timestamp = time();
$formatted_date = date("Y-m-d H:i:s", $timestamp);
echo $formatted_date; // 输出类似于: 2019-12-31 23:59:59

strtotime() 函数

strtotime() 函数将任何英文文本的日期时间描述解析为 Unix 时间戳。例如:

$timestamp = strtotime("2019-12-31");
echo $timestamp; // 输出: 1577836800,这是 2019年12月31日 00:00:00 的时间戳

getdate() 函数

getdate() 函数将一个 Unix 时间戳转换为包含各个日期部分的关联数组。例如:

$timestamp = time();
$date_array = getdate($timestamp);
print_r($date_array); // 输出类似于: Array ( [seconds] => 59 [minutes] => 30 ... )

希望这个教程能帮助你更好地理解和使用 PHP 的时间戳相关函数。