zoukankan      html  css  js  c++  java
  • php时间:获取上一个月,本月天数,下一个月

    时间戳转日期 date()   

    日期转时间戳 strtotime()

    当前时间戳time()

    获取当前月的天数:

    $i=2;
    $y=2013;
    echo date("t",strtotime("$y-$i"));

    获取本月日期:

     
    代码如下:
     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,太爽了。

    获取下月日期:

    代码如下:

    function getNextMonthDays($date){
        $timestamp=strtotime($date);
        $arr=getdate($timestamp);
        if($arr['mon'] == 12){
            $year=$arr['year'] +1;
            $month=$arr['mon'] -11;
            $firstday=$year.'-0'.$month.'-01';
            $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
        }else{
            $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)+1).'-01'));
            $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
        }
        return array($firstday,$lastday);
    }

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

    来源:https://www.cnblogs.com/liruning/p/6472501.html

  • 相关阅读:
    【vue】------ 路由创建 ------ 【William】
    【vue】------------@vue/cli3.7.0创建项目+ts-------------【William】
    【svn】--------------svn介绍------------------【William】
    【vue】------浅谈vue------【William】
    node创建服务器
    vue项目搭建
    利用vw做rem适配(纯css)
    nodejs实现md5和SHA256加密
    Cookie、session、localStorage、sessionStorage的区别
    tpc三次握手与四次挥手
  • 原文地址:https://www.cnblogs.com/laijinquan/p/9078852.html
Copyright © 2011-2022 走看看