在我的飞鸟慕鱼博客里,用不少于三篇的博文来介绍过php获取和处理时间的方法,那么今天再来水一篇关于在php的代码编程中来获取N天之前或N天之后的时间的方法。
php中想获取n天之前或n天之后的时间,要用到 strtotime() 时间处理函数,关于 strtotime() 函数的用法,你可参考本博客的《PHP中strtotime()函数,将任意日期的字符串转换成Unix时间戳》这篇文章
php 获取N天之前的时间日期的方法
例1:php获取7天之前的日期
代码:<?php
//当前时间
echo date('Y-m-d H:i:s');
//七天之前的时期
echo date("Y-m-d H:i:s",strtotime("-7 day"));
?>
输出结果:2019-11-07 23:15:40
2019-10-31 23:15:40
例2:自定义php获取N之前的日期函数
函数代码:<?php
function get_before($d){
return date("Y-m-d H:i:s",strtotime("- ".$d." day"));
}
?>
调用方法:<?php
echo get_before(8);
?>
php 获取N天之后时间日期的方法
例1:php获取3天之后的时间日期
代码:<?php
//当前时间
echo date('Y-m-d H:i:s');
//3天之后的时期
echo date("Y-m-d H:i:s",strtotime("3 day"));
?>
输出结果:2019-11-07 23:23:25
2019-11-10 23:23:25
例2:php获取n天之后的时间日期的函数
函数代码:<?php
function get_later($d){
return date("Y-m-d H:i:s",strtotime($d." day"));
}
?>
函数调用:<?php
echo get_later(7);
?>
补充说明:
灵活的运用 php 的 strtotime(),还可以获取当前时间的前N小时,后N小间,一周之前,一月之后等的时间日期。
例:<?php
//一小时之前的时间
echo strtotime("-1 hours");
//五小时之后的时间
echo strtotime("+5 hours");
//一周之后的时间
echo strtotime("+1 week");
//下周一的时间
echo strtotime("next Monday");
?>