php 获取指定月第一天和最后一天
借助于
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 参数给出的时间,如果没有提
供此参数则用系统当前时间。