PHP中的strtotime函数详细介绍
strtotime是PHP中的一个非常常用的日期时间函数,它可以将一个日期时间字符串转换为时间戳,而时间戳则可以被PHP的日期时间函数读取和格式化。本文将对strtotime函数进行详细介绍。
1. 函数定义
strtotime(string $time, int $now = time()) : int
函数参数:
$time:需要转换的日期时间字符串。
$now:可选参数,指定当前时间的时间戳。如果没有指定,就使用当前的时间戳。
函数返回值:
返回转换后的时间戳。如果转换失败,则返回false。
2. 函数使用
2.1 基本用法
strtotime函数的基本用法非常简单,只需要传入一个日期时间字符串就可以了。例如:
<?php $timeStr = '2021-03-01 09:00:00'; $timestamp = strtotime($timeStr); echo $timestamp; ?>
输出结果为:1614559200。
上面的例子中,传入了一个日期时间字符串“2021-03-01 09:00:00”,strtotime函数返回了这个日期时间的时间戳。由于没有传入第二个参数,$now默认使用当前时间。
2.2 常用参数
strtotime函数支持各种日期时间字符串格式,以下是常用的字符串格式及对应的时间戳输出:
- Y-m-d H:i:s:日期时间,例如“2021-03-01 09:00:00”。
- Y-m-d:日期,例如“2021-03-01”。
- H:i:s:时间,例如“09:00:00”或“09:00”。
例如:
<?php
echo strtotime('2021-03-01');
echo strtotime('09:00:00');
echo strtotime('2021-03-01 09:00:00');
?>
输出结果分别为:
1614556800 1614577200 1614559200
2.3 相对时间字符串
在实际使用中,strtotime最常用的功能是解析相对时间字符串,它可以将一个描述时间距离当前时间的字符串转换成一个时间戳。
常用的相对时间字符串包括:
- now:当前时间戳;
- +n min:n分钟后的时间戳;
- -n min:n分钟前的时间戳;
- +n hour:n小时后的时间戳;
- -n hour:n小时前的时间戳;
- +n day:n天后的时间戳;
- -n day:n天前的时间戳;
- +n month:n月后的时间戳;
- -n month:n月前的时间戳;
- +n year:n年后的时间戳;
- -n year:n年前的时间戳。
例如:
<?php
echo strtotime('now');
echo strtotime('+3 hours');
echo strtotime('-1 day');
?>
输出结果分别为:
1614996791 1615017586 1614903191
在使用相对时间字符串时,需要注意:
- 相对时间字符串必须以+或-开头;
- 时间单位可以是min、hour、day、month、year;
- 可以使用多个相对时间字符串,它们会被依次解析并相加。
例如:
<?php
echo strtotime('+3 hours +20 minutes');
echo strtotime('-1 day +12 hours');
?>
输出结果分别为:
1615023255 1614909591
3. 总结
strtotime函数是PHP中非常常用的一个函数,它可以将各种日期时间字符串转换为时间戳,包括相对时间字符串。掌握strtotime函数的用法,可以方便我们在PHP开发中对日期时间进行处理和计算。
