PHP按自然月计算未来日期

复制代码
背景:有时候需求需要计算从今天开始的5个月之后应该是哪一天。而跨年、每个月有大小月,或者月份中可能有28/29天,而PHP的strtotime的+n month有可能就不准确了(如:2月28日加三个月,需求可能想到5月31日,而strtotime出来则是5月28日)。为解决这个问题,方法如下
方法一:
复制代码
/**
* @param  $currTime
* 计算的时间 时间戳
* @param $month
* 增加的月份
*/
复制代码
public static function get_year_to_curtime($currTime,$month,$isDay = 1)
{
    $currY = date('Y',$currTime);
    $currM = date('m',$currTime);
    $day = date('d',$currTime);
    $futureYm=strtotime('+'.$month.'month',strtotime($currY.'-'.$currM));
    $futureMonthTotalDay = date( 't',$futureYm);
    if ($day > $futureMonthTotalDay){
        $day = $futureMonthTotalDay;
    }
    // 需求29409 解决商城与DMS时间不一致问题,DMS为前一天,因此商城也需要往前推一天
    return strtotime(date('Y-m',$futureYm).'-'.$day.'23:59:59') - 86400;
}
复制代码
方法二:
public static function get_year_to_curtime($currTime,$month)
{
    $currY = date('Y',$currTime);
    $currM = date('m',$currTime);
    $currD = date('d',$currTime);
    $nextY = $currY;
    $nextM = $currM + $month;
    if ($nextM > 12){
        $nextM = $nextM%12;
        $nextY = intval($nextM/12) + $currY;
    }
    if (in_array($nextM,[1,3,5,7,8,10,12]) && in_array($currD,[28,29,30,31])){
        $nextD = 31;
    }elseif(in_array($nextM,[4,6,7,9,11]) && in_array($currD,[28,29,30,31])){
        $nextD = 30;
    }elseif($nextM == 2 && in_array($currD,[28,29,30,31])){
        $nextD = date("t", mktime(20,20,20,2,1,$nextY));
    }else{
        $nextD = $currD;
    }
    return strtotime($nextY.'-'.$nextM.'-'.$nextD);
}
相关推荐
paterWang1 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑1 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
我真不会起名字啊2 小时前
“深入浅出”系列之杂谈篇:(3)Qt5和Qt6该学哪个?
开发语言·qt
laimaxgg2 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
水瓶丫头站住2 小时前
Qt的QStackedWidget样式设置
开发语言·qt
小钊(求职中)4 小时前
Java开发实习面试笔试题(含答案)
java·开发语言·spring boot·spring·面试·tomcat·maven
慕诗客5 小时前
QT基于Gstreamer采集的简单示例
开发语言·qt
Blasit5 小时前
C++ Qt建立一个HTTP服务器
服务器·开发语言·c++·qt·http
Victoria.a5 小时前
数组和指针常见笔试题(深度剖析)
c语言·开发语言
..过云雨5 小时前
04.类和对象(下)(初始化列表、static静态成员、友元friend[类外函数使用类私有成员]、内部类、匿名对象等)
开发语言·c++