借助于date和strtotime函數,可以輕松的獲取本月,下月以及上月的第一天和最后一天,下面分別給出其實現,其中函數的參數date格式為yyyy-MM-dd。
1,給定一個日期,獲取其本月的第一天和最后一天,代碼如下:
- function getCurMonthFirstDay($date) {
- return date('Y-m-01', strtotime($date));
- }
- function getCurMonthLastDay($date) {
- return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' +1 month -1 day'));
- }
2、給定一個日期,獲取其下月的第一天和最后一天,代碼如下:
- function getNextMonthFirstDay($date) {
- return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' +1 month'));
- }
- function getNextMonthLastDay($date) {
- return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' +2 month -1 day'));
- }
3、給定一個日期,獲取其下月的第一天和最后一天,代碼如下:
- function getPrevMonthFirstDay($date) {
- return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' -1 month'));
- }
- function getPrevMonthLastDay($date) {
- return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' -1 day'));
- }
其中strtotime函數參數"+1 month",php會根據具體月份來確定增加多少天,可能是28、29(2月)、30(小月)或 31(大月);某月的第一天 "-1 day" 自然就是上個月最后一天,php也會根據月來智能確定是28、29、30或31。
strtotime — 將任何英文文本的日期時間描述解析為 Unix 時間戳
Report a bug 說明
int strtotime ( string $time [, int $now = time() ] )
本函數預期接受一個包含美國英語日期格式的字符串并嘗試將其解析為 Unix 時間戳(自 January 1 1970 00:00:00 GMT 起的秒數),其值相對于 now 參數給出的時間,如果沒有提供此參數則用系統當前時間。
新聞熱點
疑難解答