PHP日期时间函数:格式化时间、计算时间差等
PHP中提供了许多处理日期和时间的函数,可以方便地实现时间的格式化、比较、加减等操作。以下是常用的一些日期时间函数:
一、格式化时间
1. date()函数
date()函数用于将时间格式化为指定的字符串。语法如下:
date(string $format[, int $timestamp])
参数说明:
$format:必需。要输出的时间格式。
$timestamp:可选。要格式化的时间戳。如果省略,则默认为当前时间。
示例:
echo date('Y-m-d H:i:s'); //输出当前时间,格式为“年-月-日 时:分:秒”
2. strftime()函数
strftime()函数用于将时间格式化为本地化时间字符串。语法如下:
strftime(string $format[, int $timestamp])
参数说明:
$format:必需。要输出的时间格式。
$timestamp:可选。要格式化的时间戳。如果省略,则默认为当前时间。
示例:
setlocale(LC_TIME, 'zh_CN.utf8'); //设置为中文本地化
echo strftime('%Y年%m月%d日 %H:%M:%S'); //输出当前时间,格式为“年月日 时:分:秒”
二、计算时间差
1. strtotime()函数
strtotime()函数用于将时间转换成时间戳。语法如下:
strtotime(string $time[, int $now])
参数说明:
$time:必需。要转换的时间,必须是一个字符串。
$now:可选。若指定,则表示计算从这个时间开始到指定时间的差值。如果省略,则表示计算当前时间到指定时间的差值。
示例:
echo strtotime('2022-12-31') - time(); //输出当前时间到2022年12月31日的剩余秒数
2. date_diff()函数
date_diff()函数用于计算两个日期时间之间的差值。语法如下:
date_diff(DateTimeInterface $start, DateTimeInterface $end)
参数说明:
$start:必需。表示开始时间的DateTimeInterface对象。
$end:必需。表示结束时间的DateTimeInterface对象。
示例:
$start = new DateTime('2022-01-01');
$end = new DateTime('2022-12-31');
$interval = date_diff($start, $end);
echo $interval->format('%a days'); //输出2022年剩余天数
三、其他常用函数
1. time()函数
time()函数用于获取当前时间的时间戳。语法如下:
time()
参数说明:无。
示例:
echo time(); //输出当前时间的时间戳
2. microtime()函数
microtime()函数用于获取当前时间的微秒值。语法如下:
microtime([$get_as_float])
参数说明:
$get_as_float:可选。默认为false,若为true,则返回浮点数。
示例:
echo microtime(); //输出当前时间的微秒值
以上就是PHP中常用的日期时间函数,可以方便地实现时间的格式化、比较、加减等操作。
