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啦。

  • 相关阅读:
    关于浮动清除的一些小感悟,4种方法清除浮动
    6号css学习小记
    pexpect-pxssh-登陆Linux-执行命令
    chroot命令
    Loadrunner11点击录制脚本无响应,IE页面弹不出——解决方案汇总
    JAVA实验五(网络编程)
    Java实验三
    JAVA实验二(面向对象)
    JAVA实验一
    Tfs链接错误解决方案
  • 原文地址:https://www.cnblogs.com/liruning/p/6472501.html
Copyright © 2011-2022 走看看