温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP怎么返回某个日期的前一天和后一天

发布时间:2021-08-20 09:56:58 来源:亿速云 阅读:147 作者:chen 栏目:编程语言

这篇文章主要介绍“PHP怎么返回某个日期的前一天和后一天”,在日常操作中,相信很多人在PHP怎么返回某个日期的前一天和后一天问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”PHP怎么返回某个日期的前一天和后一天”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

本文的重点是:返回给定时间的前一天、后一天的日期。那么要怎么操作呢?

其实很简单,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怎么返回某个日期的前一天和后一天

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

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

输出结果:

PHP怎么返回某个日期的前一天和后一天

分析一下关键代码:

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

PHP怎么返回某个日期的前一天和后一天

  • 当strtotime() 函数有两个参数时,第二个参数必须是时间戳格式。所以我们需要先使用一次 strtotime()函数将字符串形式的指定日期转为字符串;在使用一次 strtotime()函数进行日期的加减运算,获取算前N天和后N天的日期。

  • strtotime() 函数的返回值是时间戳格式的;所以需要使用date("Y-m-d",$time)来格式化日期时间,返回年-月-日格式的日期。

扩展知识:

  • 其实利用strtotime() 函数,不仅可以获取前N天和后N天日期,还可以获取前N月和后N月日期前N年和后N年日期

<?php
	$month2 = strtotime("-1 months",strtotime("2000-1-2"));
	$month3 = strtotime("+2 months",strtotime("2000-1-2"));
	echo date("Y-m-d",$month2)."<br>";
	echo date("Y-m-d",$month3)."<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>";
?>

输出结果:

PHP怎么返回某个日期的前一天和后一天

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

PHP怎么返回某个日期的前一天和后一天

实现代码:

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

输出结果:

PHP怎么返回某个日期的前一天和后一天

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

到此,关于“PHP怎么返回某个日期的前一天和后一天”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI