PHP函数运用之返回某个日期的前一天和后一天
时间:2021-08-31
来源:互联网
今天PHP爱好者给大家带来PHP函数运用之返回某个日期的前一天和后一天的方法,在上一篇文章《PHP函数运用之计算截止某年某月某日共有多少天》中,我们介绍了利用strtotime()函数计算两个给定日期间时间差的方法。这次我们来来看看给大一个指定日期,怎么返回它前一天和后一天的日期。感兴趣的朋友可以学习了解一下~希望对大家有所帮助。
本文的重点是:返回给定时间的前一天、后一天的日期。那么要怎么操作呢?
其实很简单,PHP内置的strtotime() 函数就可以实现这个操作!下面来看看我的实现方法:
返回某个日期的前一天的实现代码
<?php
function GetTime($year,$month,$day){
$timestamp = strtotime("{$year}-{$month}-{$day}");
$time = strtotime("-1 days",$timestamp);
echo date("Y-m-d",$time)."<br>";
}
GetTime(2000,3,1);
GetTime(2021,1,1);
?>
输出结果:
返回某个日期的后一天的实现代码
<?php
function GetTime($year,$month,$day){
$timestamp = strtotime("{$year}-{$month}-{$day}");
$time = strtotime("+1 days",$timestamp);
echo date("Y-m-d",$time)."<br>";
}
GetTime(2000,2,28);
GetTime(2021,2,28);
?>
输出结果:
分析一下关键代码:
strtotime() 函数有两种用法:一种是将字符串形式的、用英文文本描述的日期时间解析为 UNIX 时间戳,一种是用来计算一些日期时间的间隔。
我们利用strtotime() 函数计算时间间隔的功能,使用
strtotime("-1 days",$timestamp)
和strtotime("+1 days",$timestamp)
计算出指定日期前一天和后一天的日期。"
-1 days
"就是减一天,"+1 days
"就是加一天;观察规律,我们还可以根据需要获取前N天,后N天的日期
<?php
function GetTime($year,$month,$day){
$timestamp = strtotime("{$year}-{$month}-{$day}");
$time1 = strtotime("-2 days",$timestamp);
$time2 = strtotime("+3 days",$timestamp);
echo date("Y-m-d",$time1)."<br>";
echo date("Y-m-d",$time2)."<br>";
}
GetTime(2000,3,5);
?>
当strtotime() 函数有两个参数时,第二个参数必须是时间戳格式。所以我们需要先使用一次 strtotime()函数将字符串形式的指定日期转为字符串;在使用一次 strtotime()函数进行日期的加减运算,获取算前N天和后N天的日期。
strtotime() 函数的返回值是时间戳格式的;所以需要使用
date("Y-m-d",$time)
来格式化日期时间,返回年-月-日
格式的日期。
扩展知识:
其实利用strtotime() 函数,不仅可以获取前N天和后N天日期,还可以获取前N月和后N月日期、前N年和后N年日期:
<?php
$month1 = strtotime("-1 months",strtotime("2000-1-2"));
$month2 = strtotime("+2 months",strtotime("2000-1-2"));
echo date("Y-m-d",$month1)."<br>";
echo date("Y-m-d",$month2)."<br><br>";
$year1 = strtotime("-1 years",strtotime("2000-1-2"));
$year2 = strtotime("+2 years",strtotime("2000-1-2"));
echo date("Y-m-d",$year1)."<br>";
echo date("Y-m-d",$year2)."<br>";
?>
输出结果:
想要获取前一周和后一周的日期,也可以利用strtotime() 函数。例如:当前日期2021-8-19,前一周和后一周的日期为:
实现代码:
<?php
header("content-type:text/html;charset=utf-8");
$start = time(); //获取当前时间的时间戳
echo "当前日期为:".date('Y-m-d',$start)."<br />";
$interval = 7 * 24 * 3600; //一周总共的秒数
$previous_week = $start - $interval; //当前时间的时间戳 减去 一周总共的秒数
$next_week = $start + $interval; //当前时间的时间戳 加上 一周总共的秒数
echo "前一周日期为:".date('Y-m-d',$previous_week)."<br />";
echo "后一周日期为:".date('Y-m-d',$next_week)."<br />";
?>
输出结果:
前后两个日期正好相差 7 天。这其实就是计算时间差的一种逆运用。
以上就是PHP函数运用之返回某个日期的前一天和后一天的详细内容,更多请关注php爱好者其它相关文章!
-
拉里芬克 时间:2025-05-10
-
huobi怎么充钱进去?huobi充值交易教程 时间:2025-05-10
-
vc是什麼 时间:2025-05-10
-
INST币为何能一个月涨3倍之多?INST代币经济学详解 时间:2025-05-10
-
七日世界寻宝客任务怎么过-寻宝客剧情 时间:2025-05-10
-
xrp值得投资吗 时间:2025-05-10
今日更新
-
最新消息!Go 1.17 正式发布啦!
阅读:18
-
JS数组学习之怎么去除头部或尾部元素
阅读:18
-
ThinkPHP有三种方式收集表单数据
阅读:18
-
PHP函数运用之利用字符串函数来提取文件的扩展名
阅读:18
-
一招教你使用html给图片添加边框效果(代码详解)
阅读:18
-
浅析Node.js包管理工具 npm 和 yarn 的用法
阅读:18
-
PHP函数运用之怎么进行进制的转换
阅读:18
-
PHP数组学习之怎么截取元素片段(两种方式)
阅读:18
-
如何用js从字符串中删除所有非ASCII字符?(两种方法)
阅读:18
-
一招教你怎么使用ps将文字边缘添加溶解效果(技巧分享)
阅读:18