首先要了解一下关于时间方面的函数:date() 和 strtotime()。
date()函数:
语法:date(format,timestamp);format:时间输出根据这个格式输出。timestamp:可选参数,使用的是 Unix 时间戳,不选默认使用当前环境时间。
例子:
$mytime= date("Y-m-d H:i:s");
echo $mytime;
效果如图所示:
strtotime()函数(将日期或时间字符窜描述解析为 Unix 时间戳):
语法:strtotime(time,now);time:指定的日期或者时间。now:可选参数,规定用来计算返回值的时间戳,默认是当前时间(一般不写)
参数time比较有意思,可以使用描述来解析。
例子:
echo "现在:".strtotime("now") . " ";
echo "1小时之后:".strtotime("+1 hours") . " ";
echo "1小时之前:".strtotime("-1 hours") . " ";
echo "上一个星期天:".strtotime("last Sunday");
效果如图:
现在使用上面两个组合获取去年的今天。
首先使用strtotime(),获取是时间戳,然后使用date()函数格式化时间。
代码:
echo "今天日期:".date("Y-m-d H:i:s", strtotime("now"));
echo "去年今天:".date("Y-m-d H:i:s", strtotime("-1 year"));
效果如图: