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);
}
相关推荐
listhi52010 分钟前
基于改进SET的时频分析MATLAB实现
开发语言·算法·matlab
友友马1 小时前
『QT』事件处理机制详解 (一)
开发语言·qt
孤独斗士1 小时前
maven的pom文件总结
java·开发语言
confiself1 小时前
通义灵码分析ms-swift框架中CHORD算法实现
开发语言·算法·swift
1024小神1 小时前
在 Swift 中,self. 的使用遵循明确的规则
开发语言·ios·swift
Swift社区1 小时前
Swift 类型系统升级:当协议遇上不可拷贝的类型
开发语言·ios·swift
chengpei1471 小时前
I²C协议简介
c语言·开发语言
唐古乌梁海1 小时前
【IT】常见计算机编程语言多继承问题
开发语言
雨中散步撒哈拉1 小时前
18、做中学 | 初升高 | 考场一 | 面向过程-家庭收支记账软件
开发语言·后端·golang
翔云 OCR API2 小时前
承兑汇票识别接口技术解析-开发者接口
开发语言·前端·数据库·人工智能·ocr