一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

php 获取指定月第一天和最后一天

时间:2013-08-12 编辑:简简单单 来源:一聚教程网

借助于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 参数给出的时间,如果没有提供此参数则用系统当前时间。

热门栏目