HRZ

在指定日期基础上增减月份

需要定义一个方法

    function MonthShifter(DateTime $aDate,$months) {
        $dateA = clone($aDate);
        $dateB = clone($aDate);
        $plusMonths = clone($dateA->modify($months . ' Month'));
        //check whether reversing the month addition gives us the original day back
        if($dateB != $dateA->modify($months*-1 . ' Month')){
            $result = $plusMonths->modify('last day of last month');
        } elseif($aDate == $dateB->modify('last day of this month')){
            $result =  $plusMonths->modify('last day of this month');
        } else {
            $result = $plusMonths;
        }
        return $result;
    }

调用方法

$time = new \DateTime('2021-2-21');
$result = MonthShifter($time,12)->format(('Y-m-d'));
var_dump($result);die;