PHP日期函数使用教程:时间格式化、转换和计算
在PHP中,有很多内置的日期函数,可以帮助我们处理和操作日期和时间。本文将介绍一些常用的日期函数,包括时间格式化、转换和计算。
时间格式化
PHP中最基本的日期格式化函数就是date()函数,该函数可以将一个时间戳或日期字符串格式化为指定的日期格式。下面是一个简单的例子:
$timestamp = time();//获取当前时间戳
$date = date("Y年m月d日 H:i:s", $timestamp);
echo $date;//输出结果:2022年01月21日 15:02:31
在上面的例子中,我们使用了time()函数获取当前的时间戳,然后使用date()函数将时间戳格式化为指定的日期格式,并输出结果。
除了使用时间戳获取当前时间外,还可以使用strtotime()函数将日期字符串转换为时间戳。下面是一个例子:
$date_str = '2022-01-21 15:02:31';
$timestamp = strtotime($date_str);
$date = date("Y年m月d日 H:i:s", $timestamp);
echo $date;//输出结果:2022年01月21日 15:02:31
在上面的例子中,我们使用了strtotime()函数将日期字符串转换为时间戳,然后再使用date()函数格式化时间戳为指定的日期格式,并输出结果。
时间转换
除了将日期字符串转换为时间戳,PHP还提供了一些函数可以将时间戳或日期字符串转换为其它日期格式。下面是一些常用的时间转换函数:
1. strtotime():将日期字符串转换为时间戳。
$date_str = '2022-01-21 15:02:31'; $timestamp = strtotime($date_str); echo $timestamp;//输出结果:1642753351
2. getdate():将时间戳转换为关联数组。
$timestamp = time();//获取当前时间戳
$date_arr = getdate($timestamp);
print_r($date_arr);
/*
输出结果:
Array
(
[seconds] => 33
[minutes] => 11
[hours] => 16
[mday] => 21
[wday] => 5
[mon] => 1
[year] => 2022
[yday] => 20
[weekday] => Friday
[month] => January
[0] => 1642770693
)
*/
3. strftime():将时间戳格式化为本地日期/时间。
$timestamp = time();//获取当前时间戳
$date_str = strftime("%Y年%m月%d日 %H:%M:%S", $timestamp);
echo $date_str;//输出结果:2022年01月21日 16:06:33
在上面的例子中,我们使用了strftime()函数将时间戳格式化为本地日期/时间,并输出结果。
时间计算
PHP也提供了一些函数可以对时间进行计算,如计算时间差、增加或减少时间等。下面是一些常用的时间计算函数:
1. time():获取当前时间戳。
$timestamp = time();//获取当前时间戳 echo $timestamp;//输出结果:1642771293
2. mktime():生成一个时间戳。
$timestamp = mktime(10, 30, 0, 1, 21, 2022);//生成一个时间戳 echo $timestamp;//输出结果:1642746600
在上面的例子中,我们使用了mktime()函数生成了一个时间戳,表示2022年1月21日10时30分0秒。
3. strtotime():将日期字符串转换为时间戳。
$date_str1 = '2022-01-21 15:02:31'; $date_str2 = '2022-01-23 14:03:32'; $timestamp1 = strtotime($date_str1); $timestamp2 = strtotime($date_str2); $time_diff = $timestamp2 - $timestamp1; echo $time_diff;//输出结果:172201
在上面的例子中,我们使用了strtotime()函数将两个日期字符串转换为时间戳,然后计算出时间差,并输出结果,表示两个日期之间相差172201秒。
4. date_add()和date_sub():增加或减少时间。
$date = date_create('2022-01-21 15:02:31');
date_add($date, date_interval_create_from_date_string('1 day 2 hours'));//增加1天2小时
echo date_format($date, 'Y-m-d H:i:s');//输出结果:2022-01-22 17:02:31
$date = date_create('2022-01-21 15:02:31');
date_sub($date, date_interval_create_from_date_string('3 hours 30 minutes'));//减少3小时30分钟
echo date_format($date, 'Y-m-d H:i:s');//输出结果:2022-01-21 11:32:31
在上面的例子中,我们使用了date_create()函数创建一个日期对象,然后使用date_add()和date_sub()函数来增加或减少时间,并最终使用date_format()函数格式化输出结果。
