`

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

    博客分类:
  • PHP
阅读更多

 

PHP获取某一天前后任意时间

date("Y-m-d",strtotime('-30 days',strtotime('2016-9-30')));

 

 

借助于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。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics