[转]php 获取本月最后一天日期的实现思路

今天在laravel中国社区 上面看到这个文章还 挺有意思的,就转来学习一下

给一个时间,获取这个月的结束的日期。比如 输入’2018-12-04’ 输出’2018-12-31’

方法一

如果我们从1,3,5,7,8,10,12有31天,剩下的有30天,2月比较特殊 平年2月28,闰年2月29这个角度来实现的话:

function monthDay($date) {
     $month31 = [1, 3, 5, 7, 8, 10, 12];
    list($year, $month) = explode('-',$date);
    if ($month != 2) {
        if (in_array($month, $month31)) {
            return "{$year}-{$month}-31";
        } else {
            return "{$year}-{$month}-30";
        }
    }
      if (  $year%4==0  && ($year%100!=0 ||  $year%400==0 ) ){
        return "{$year}-{$month}-29";
    }else{
        return "{$year}-{$month}-28";
    }
}

方法二

方法一的代码看着没啥问题,但是可能是一种特别复杂的实现方式,它考虑的因素比较多。另一种思路就是:本月的天数 = 下月1号 - 本月 1号。

但是有个特殊的情况,如果是年底,那么12月的下一月就是新的一年的1月。

function endDayOfMonth($date) {
    list($year, $month) = explode('-',$date);
    $nextYear = $year;
    $nexMonth = $month+1;
    //如果是年底12月 下个月就是1月
    if($month == 12) {
        $nexMonth = "01";
        $nextYear = $year+1;
    }
    $begin = "{$year}-{$month}-01 00:00:00";
    $end = "{$nextYear}-{$nexMonth}-01 00:00:00";
    $day = (strtotime($end) - strtotime($begin) )/ (24*60*60);
    return "{$year}-{$month}-{$day}";
}

方法三

方法二的方法其实已经差不多接近了,但是还是可能不够特别好的。因为我们不需要算天数。我们知道新的一个月的第一天,减去一个1,就是当月的最后一秒。

function endDayOfMonth($date) {
    list($year, $month) = explode('-',$date);
    $nextYear = $year;
    $nexMonth = $month+1;
    //如果是年底12月 下个月就是1月
    if($month == 12) {
        $nexMonth = "01";
        $nextYear = $year+1;
    }
    $end = "{$nextYear}-{$nexMonth}-01 00:00:00";
    $endTimeStamp = strtotime($end) - 1 ;
    return date('Y-m-d',$endTimeStamp);
}

PHP带函数实现

其实php自带的有多种实现的方式,比如date、DateTime、strtotime等

php date 函数格式化

t 指定月份的天数; 如: “28” 至 “31”

$date = '2018-08-08';
echo date('Y-m-t',strtotime($date));

strtotime 字符串时间修饰词

last day of this month 时间字符 类似我们常说的 -1 day

echo date('Y-m-d',strtotime("last day of this month",strtotime('2018-02-01')));
echo date('Y-m-d',strtotime("last day of 2018-02"));

php DateTime类 面向对象方式

$date = new \DateTime('2000-02-01');
$date->modify('last day of this month');
echo $date->format('Y-m-d');

其实这题主要是我们常见的面试题演变的。主要是想看怎么考虑问题,很多的时候,我们陷入了一个误区里,考虑了复杂的实现,其实就是两个函数的使用,一个是 date 和 strtotime

求昨天的日期,strtotime('-1 day')

当然使用php内置函数 时最简单的,但是很多时候第一时间没有想到或者不知道内置函数有这个功能,就会采用前两种方法。所以说 PHP内置函数还是很香的!!!!

接下来自己在记录一些 平时不常用的 date 用法

date('L') // 1是闰年 0 不是
date('l') //今天是周几
date('D') //今天是周几缩写
date('w'); //周几的数字展示
date('W') //一年中的周数
date('t') //本月天数
date('z') //今天是今年的第多少天
date('T') //大写T表示服务器的时间区域设置
date('I') //大写I表示判断当前是否为夏令时,为真返回1,否则为0
date('U') = time() //大写U表示从1970年1月1日到现在的总秒数,就是Unix时间纪元的UNIX时间戳。
date('C')  //小写c表示ISO8601日期,日期格式为YYYY-MM-DD,用字母T来间隔日期和时间,时间格式为HH:MM:SS,时区使用格林威
date('r') //小写r表示RFC822日期。
mktime() //函数可为指定的日期返回 Unix 时间戳。
checkdate($month,$date,$year) //如果应用的值构成一个有效日期,则该函数返回为真。例如,对于错误日期2005年2月31日,此函数返回为假。
getdate() //获得一系列离散的,容易分离的日期/时间值。