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 小时前
Java 篇-项目实战-AI 天机学堂(从 0 到 1)-day1
java·开发语言
楼田莉子6 小时前
C++17新特性:__had_include/属性/求值顺序规则
开发语言·c++·后端
香蕉鼠片6 小时前
Python进阶学习
开发语言·python
摇滚侠6 小时前
Java 零基础全套教程,File 类与 IO 流,笔记 177-178
java·开发语言·笔记
ytttr8737 小时前
OPC UA 协议栈 C 语言实现
c语言·开发语言·mfc
song5017 小时前
Ascend C 算子开发:从入门到上手
c语言·开发语言·图像处理·人工智能·分布式·flutter·交互
小a杰.7 小时前
Ascend C编程语言进阶:高性能算子开发技巧
android·c语言·开发语言
全糖可乐气泡水7 小时前
Codex适配国产信创环境安装部署与技术适配全解析
开发语言·git·python·算法·百度
雨落在了我的手上7 小时前
初始java(十):类和对象(⼆)
java·开发语言
LeocenaY7 小时前
搜集的一些测开面试题
开发语言·python