您的位置:首页 > 编程语言 > PHP开发

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

2013-11-28 14:37 225 查看
转载:http://www.netingcn.com/php-%E8%8E%B7%E5%8F%96%E6%9C%88%E7%AC%AC%E4%B8%80%E5%A4%A9%E5%92%8C%E6%9C%80%E5%90%8E%E4%B8%80%E5%A4%A9.html

借助于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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐