• 技术文章 >后端开发 >PHP问题

    PHP函数运用之返回某个日期的前一天和后一天

    青灯夜游青灯夜游2021-08-19 18:56:56原创379
    在上一篇文章《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

    分析一下关键代码:

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

    扩展知识:

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

    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中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    上一篇:PHP函数运用之计算截止某年某月某日共有多少天 下一篇:PHP函数运用之怎么进行进制的转换

    相关文章推荐

    • PHP日期时间运用七:获取某个国家的日期和星期• PHP日期时间运用八:添加或减去特定日期的天数• PHP日期时间运用十:将秒数转成格式为“天时分秒”• PHP日期时间运用十一:三种方法比较两个指定的日期

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网