zoukankan      html  css  js  c++  java
  • PHP获取上个月、下个月、本月的日期

    获取本月日期:
     
    代码如下:
    1 function getMonth($date){
    2      $firstday = date("Y-m-01",strtotime($date));
    3      $lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day"));
    4      return array($firstday,$lastday);
    5  }

    $firstday是月份的第一天,假如$date是2014-2这样的话,$firstday就会是2014-02-01,然后根据$firstday加一个月就是2014-03-01,再减一天就是2014-02-28,用date()和strtotime()真是太方便了。

    获取上月日期:
     
    代码如下:
    1 function getlastMonthDays($date){
    2      $timestamp=strtotime($date);
    3      $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1).'-01'));
    4      $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
    5      return array($firstday,$lastday);
    6  }

    上月日期需要先获取一个时间戳,然后在月份上-1就OK了,超智能的date()会把2014-0-1这种东西转换成2013-12-01,太爽了。

    获取下月日期:

    代码如下:

    复制代码
     1 function getNextMonthDays($date){
     2     $timestamp=strtotime($date);
     3     $arr=getdate($timestamp);
     4     if($arr['mon'] == 12){
     5         $year=$arr['year'] +1;
     6         $month=$arr['mon'] -11;
     7         $firstday=$year.'-0'.$month.'-01';
     8         $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
     9     }else{
    10         $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)+1).'-01'));
    11         $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
    12     }
    13     return array($firstday,$lastday);
    14 }
    复制代码

    下月日期的代码看起来比较长一点,因为date()转不了类似2014-13-01这种东西,它会直接回到1970,所以前面需要处理一下12月的问题,除了12月就直接月份+1就OK啦。

  • 相关阅读:
    Groovy 闭包_胖子的家_百度空间
    活动 | Think+大声思考
    微软对联背后的故事
    核心技术研发工程师 百度在线网络技术(北京)有限公司 庞果网Pongo.cn
    Groovy 闭包深入浅出 终点就是起点 ITeye技术网站
    Groovy闭包深入学习 [203] 一直都有新高度 ITeye技术网站
    用groovy写抓票程序
    eating machine=chi huo
    sql case when学习
    韦式词典发音
  • 原文地址:https://www.cnblogs.com/liruning/p/6472501.html
Copyright © 2011-2022 走看看