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);
}
相关推荐
青槿吖21 分钟前
第二篇:告别XML臃肿配置!Spring注解式IOC/DI保姆级教程,从入门到真香
xml·java·开发语言·数据库·后端·sql·spring
t1987512824 分钟前
TOA定位算法MATLAB实现(二维三维场景)
开发语言·算法·matlab
梦想的旅途225 分钟前
如何通过 QiWe API 实现企业微信主动发消息
开发语言·python
jllllyuz25 分钟前
粒子群算法解决资源分配问题的MATLAB实现
开发语言·算法·matlab
凌晨一点的秃头猪35 分钟前
Python文件操作
开发语言·python
pangares1 小时前
防火墙安全策略(基本配置)
服务器·php·apache
myloveasuka1 小时前
C++进阶:利用作用域解析运算符 :: 突破多态与变量隐藏
开发语言·c++
OxyTheCrack1 小时前
【C++】详细拆解std::mutex的底层原理
linux·开发语言·c++·笔记
云栖梦泽2 小时前
易语言开发从入门到精通:进阶篇·网络爬虫与数据采集分析系统深度实战
开发语言
lsx2024062 小时前
XSLT `<sort>` 元素详解
开发语言