轻松学习PHP日期函数:strtotime()的使用方法
发布时间:2023-06-21 03:54:12
在PHP编程中,日期和时间相关的操作经常用到,而strtotime()函数就是PHP日期函数中比较常用的一个。它可以把人类易读的时间格式解析成Unix时间戳,或者把时间戳格式化成人类可读的时间格式。本文将介绍strtotime()函数的用法。
1.将日期格式转成时间戳
strtotime()函数最常用的用途就是把日期格式转换成时间戳,也就是一个整数值,表示从1970年1月1日0时0分0秒开始到指定日期时间的秒数。其语法如下:
strtotime ( string $time [, int $now = time() ] ) : int
其中,$time是要转换的日期字符串,$now是可选参数,默认值是当前时间戳。该函数返回转换后的时间戳。
例如:
echo strtotime("2019-11-15 10:19:17");// 输出1573822757
2.将时间戳转成日期格式
同时,strtotime()函数也可以把时间戳格式化成日期格式,其语法如下:
date ( string $format [, int $timestamp = time() ] ) : string
其中,$format是日期格式字符串,$timestamp是可选参数,默认值是当前时间戳。该函数返回格式化后的日期字符串。
例如:
echo date("Y-m-d H:i:s",1573822757);// 输出2019-11-15 10:19:17
3.根据某个格式把日期字符串转换成时间戳
strtotime()函数也可以按照各种格式解析日期字符串,例如:
echo strtotime("3 October 2005");// 输出1128312000
echo strtotime("2019-11-15 10:19:17");// 输出1573822757
echo strtotime("+1 day");// 输出当前时间加一天后的时间戳
echo strtotime("+1 week");// 输出当前时间加一周后的时间戳
echo strtotime("+1 month");// 输出当前时间加一个月后的时间戳
4.字符串日期的相加
如果需要对日期字符串进行加减运算,可使用strtotime()函数,例如:
echo date("Y-m-d H:i:s",strtotime("2019-11-15 10:19:17 +1 day"));// 输出2019-11-16 10:19:17
如果是要减去一段时间,可以在字符串前面加一个“-”符号,例如:
echo date("Y-m-d H:i:s",strtotime("2019-11-15 10:19:17 -1 week"));// 输出2019-11-08 10:19:17
5.其他用法
如果我们需要对字符串进行格式化时,也可以在date()函数中嵌套使用strtotime()函数,例如:
echo date("Y-m-d H:i:s",strtotime("+1 day", strtotime("2019-11-15 10:19:17")));// 输出2019-11-16 10:19:17
参考资料:
https://www.php.net/manual/zh/function.strtotime.php
https://www.php.net/manual/zh/function.date.php
