PHP日期时间函数——strtotime()的使用方法详解
发布时间:2023-06-16 13:47:46
PHP中的strtotime()函数是一个非常有用的函数,可以将日期时间字符串转换为Unix时间戳。它的使用非常灵活,可以处理各种日期时间格式,并支持一些常用的时间间隔操作。
strtotime()函数的语法如下:
int strtotime(string $time [, int $now = time() ]);
其中,$time表示指定的日期时间字符串,$now表示可选的将 strtotime() 得到的时间戳作为第二个参数传递给date()函数。
下面我们来看一下strtotime()函数的使用方法及例子。
1. 转换日期时间字符串为Unix时间戳
$time = '2021-01-01 00:00:00'; $timestamp = strtotime($time); echo $timestamp; //输出:1609430400
2. 转换人类可读时间格式为Unix时间戳
$timestamp = strtotime('10 September 2021 10:10:10');
echo $timestamp; //输出:1631237410
3. 转换相对时间为Unix时间戳
$timestamp = strtotime('+1 day'); //明天的这个时候
echo $timestamp; //输出:1630863506
4. 转换相对时间并结合特定时间
$timestamp = strtotime('next Friday 6pm');
echo $timestamp; //输出下周五下午6点的时间戳
5. 转换相对时间并与特定日期时间结合
$timestamp = strtotime('next Friday', strtotime('2021-01-01 00:00:00'));
echo $timestamp; //输出2021年1月8日的时间戳
6. 计算两个日期之间的时间间隔
$start_date = strtotime('2021-01-01');
$end_date = strtotime('2022-01-01');
$diff = ($end_date - $start_date) / (60 * 60 * 24); //相差天数
echo $diff; //输出:365
7. 计算未来时间
$future_time = time() + (60 * 60 * 24 * 7); //现在时间加一周的秒数
echo date('Y-m-d H:i:s', $future_time); //输出:未来一周的这个时间
总的来说,strtotime()函数是一个快速而便捷的工具,它可以轻松地转换日期时间字符串、计算时间间隔以及生成未来时间等。熟练掌握该函数的使用方法,可以大大提高开发效率。
