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);
}
相关推荐
李永奉4 小时前
C语言-嵌入式开发C语言常用预处理指令合集
c语言·开发语言
上海安当技术4 小时前
敏感数据怎么防拖库?信封加密(DEK+KEK 二层密钥)架构设计与 Java 实战
java·开发语言·python
我是唐青枫4 小时前
Java JCommander 实战详解:用注解解析命令行参数
java·开发语言
大鹏说大话5 小时前
C++ 内存布局详解:类、虚函数、虚表底层原理
java·开发语言
键盘会跳舞5 小时前
C++:容器适配器 queue 的源码级拆解
开发语言·c++·queue
Loge编程生活6 小时前
打卡信奥刷题(3449)用C++实现信奥题 P10429 [蓝桥杯 2024 省 B] 拔河
开发语言·数据结构·c++·算法·青少年编程
在世修行7 小时前
从零打造 C# 工业视觉检测系统(八):Modbus RTU 协议解析与 PLC 剔除控制实战
开发语言·c#
sunburn-7 小时前
Java 队列全面详解:从入门到面试实战
java·开发语言·汇编·ide·idea
AI直播技术杂谈7 小时前
AI直播推流链路中延迟优化的通用技术方案
开发语言·人工智能·php
vx-程序开发7 小时前
springboot农产品运输服务平台---附源码75498
java·javascript·spring boot·python·eclipse·django·php