水滴石主要分享一些生活中的经验和IT技术自学过程中积累的技术、学习资源和软件资源等。座右铭:坚持+自律=开挂人生。
当前位置: 首页 > 网站建设 > php获取前一天,前一周,前一月,前一年的函数

php获取前一天,前一周,前一月,前一年的函数

标签:

本文介绍了php如何获取前一天、前一周、前一月、前一年的时间和指定日期的前一天、前一周、前一月、前一年的函数方法。

php时间函数

获取前一天、前一周、前一月、前一年的时间的函数

date_default_timezone_set("PRC");
//当前时间
$now=mktime(0, 0, 0, date("m"), date("d")-1, date("Y"));
//前一天
$yesterday=date("Y-m-d H:i:s", strtotime("-1 day"));
//前一周
$lastweek=date("Y-m-d H:i:s", strtotime("-1 week"));
//前一月
$lastmonth=date("Y-m-d H:i:s", strtotime("-1 month"));
//前一年

$lastyear=date("Y-m-d H:i:s", strtotime("-1 year"));


获得定日期的前一天、前一周、前一月、前一年的函数方法

dump(date('Y-m-d', strtotime('2018-10-1 +1 day')));
 
dump(date('Y-m-d', strtotime('2018-10-1 +1 week')));
 
dump(date('Y-m-d', strtotime('2018-10-1 +1 month')));
 
dump(date('Y-m-d', strtotime('2018-10-1 +1 year')));
 
dump(date('Y-m-d', strtotime('2018-10-1 -1 day')));
 
dump(date('Y-m-d', strtotime('2018-10-1 -1 week')));
 
dump(date('Y-m-d', strtotime('2018-10-1 -1 month')));
 
dump(date('Y-m-d', strtotime('2018-10-1 -1 year')));
同理,把2018-10-1换成变量,就可以做很多事了!

ps 由于每个月份的天数不一样 +/- 1 month 特殊日期会有误差

//获取上一个月日期方法  
public function getBeforeMonthDate($currentDate)
{
    $currentMonthDay = date('t', strtotime($currentDate));
    $currentDay      = date('d', strtotime($currentDate));
    $yearMonth       = date('Y-m', strtotime($currentDate));
    $beforeMonth     = date('Y-m-d', strtotime("$yearMonth -1 month"));
    $beforeMonthDay  = date('t', strtotime($beforeMonth));
    if ($beforeMonthDay < $currentMonthDay && $beforeMonthDay < $currentDay) {
        $beforeDate = date("Y-m-d", strtotime("last day of -1 month", strtotime($currentDate)));
    } else {
        $beforeDate = date('Y-m-d', strtotime("$currentDate -1 month"));
    }
    return $beforeDate;
}


这些php时间函数基本上就能满足在建站过程中的大部分需求了,如果有特殊需求的话请在php手册中查询,希望能够对大家有所帮助。

更多相关推荐

版权保护:本文《php获取前一天,前一周,前一月,前一年的函数》由<我爱分享>原创,转载请保留链接:http://www.shuidi365.cn/site/81.html

相关推荐
  • 没有相关文章

此博客主要用来分享、推荐自己日常、学习过程中感觉比较实用的经验、IT技术和一些比较好的资源(各种软件、各种开发手册、各种学习资料、各种视频教程等),希望对大家有所帮助,有问题请留言,欢迎来交流,联系QQ邮箱/微信:342807450

合作伙伴
冀ICP备19020226号-1 冀公网安备 13010902000246号