[轉]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() //獲得一系列離散的,容易分離的日期/時間值。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM