如何使用PHP的strtotime函数来转换日期时间格式
1. 什么是strtotime函数?
strtotime函数是PHP语言中的一个内置函数,主要用于将人类可读的日期时间格式转换为Unix时间戳。Unix时间戳是从1970年1月1日至今的秒数。
2. 如何使用strtotime函数?
strtotime函数的基本语法如下:strtotime ( string $time , int $now = time() ):将字符串转换成Unix时间戳
其中,$time是要转换的日期时间字符串,$now表示当前时间的时间戳,可选参数。
例如:
$timestamp = strtotime('2022-01-01 00:00:00');
echo $timestamp; //输出:1640995200
上述代码将字符串"2022-01-01 00:00:00"转换成了Unix时间戳。
3. strtotime函数支持的日期时间格式
strtotime函数支持多种日期时间格式,以下是一些常用的格式:
- 'YYYY-MM-DD' :日期格式
- 'YYYY/MM/DD' :日期格式
- 'YYYY-MM-DD HH:MM:SS' :完整时间格式
- 'YYYY/MM/DD HH:MM:SS' :完整时间格式
- 'now' :表示当前日期时间
- '+X day' :X表示天数,表示当前日期时间的X天后
- '-X day' :X表示天数,表示当前日期时间的X天前
- '+X month' :X表示月份,表示当前日期时间的X个月后
- '-X month' :X表示月份,表示当前日期时间的X个月前
- '+X year' :X表示年份,表示当前日期时间的X年后
- '-X year' :X表示年份,表示当前日期时间的X年前
例如:
$timestamp1 = strtotime('2022-01-01'); //输出:1640995200
$timestamp2 = strtotime('2022/01/01'); //输出:1640995200
$timestamp3 = strtotime('2022-01-01 00:00:00'); //输出:1640995200
$timestamp4 = strtotime('2022/01/01 00:00:00'); //输出:1640995200
$timestamp5 = strtotime('now'); //输出当前时间的时间戳
$timestamp6 = strtotime('+1 day'); //输出当前时间加1天后的时间戳
$timestamp7 = strtotime('-1 month'); //输出当前时间减1个月后的时间戳
$timestamp8 = strtotime('+1 year'); //输出当前时间加1年后的时间戳
4. strtotime函数的注意事项
- strtotime函数输入的日期时间字符串必须遵循一定的格式,否则会产生错误。
- strtotime函数的返回值是一个整数型Unix时间戳,需要用date函数进行格式化输出。
- strtotime函数只能处理1970年以后的时间戳,无法处理其它的时间戳。
5. 示例
下面是一个示例,演示如何使用strtotime函数将日期时间字符串转换为Unix时间戳,并以指定的日期时间格式输出:
$datetime = '2022-01-01 00:00:00';
$timestamp = strtotime($datetime);
$date = date('Y年m月d日 H时i分s秒', $timestamp);
echo $date; //输出:2022年01月01日 00时00分00秒
在这个示例中,我们首先使用strtotime函数将日期时间字符串"2022-01-01 00:00:00"转换成了Unix时间戳。然后使用date函数将Unix时间戳转换成了指定的日期时间格式,并输出。
