在上一篇文章《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);
?>

输出结果:

1.png

  • 返回某个日期的后一天的实现代码

<?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);
?>

输出结果:

2.png

分析一下关键代码:

  • 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);
?>

3.png

  • 当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>";
?>

输出结果:

4.png

  • 想要获取前一周和后一周的日期,也可以利用strtotime() 函数。例如:当前日期2021-8-19,前一周和后一周的日期为:

6.png

实现代码:

<?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 />";
?>

输出结果:

5.png

前后两个日期正好相差 7 天。这其实就是计算时间差的一种逆运用。

好了就说到这里了,有其他想知道的,可以点击这个哦。→ →php视频教程

以上就是PHP函数运用之返回某个日期的前一天和后一天的详细内容,更多请关注亿码酷站其它相关文章!


PHP函数运用之返回某个日期的前一天和后一天
—–文章转载自PHP中文网如有侵权请联系ymkuzhan@126.com删除

云服务器推荐