欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

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

程序员文章站 2022-06-14 08:23:36
...

借助于date和strtotime函数,可以轻松的获取本月、下月以及上月的第一天和最后一天,下面分别给出其实现。其中函数的参数date格式为yyyy-MM-dd。 1、给定一个日期,获取其本月的第一天和最后一天 function getCurMonthFirstDay($date) { return date('Y-m-01

借助于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 的功能很强大,详细用法可以查看官方文档:http://php.net/manual/zh/function.strtotime.php 。