PHP 日期加月份

发布时间 2023-10-13 15:54:43作者: 磊有三颗小石头
function setMonth($time, $length){
    // $time => 时间戳  $length => 加减几月(数字)
    if (!is_numeric($time)) $time = strtotime($time);
    if ($length > 0) $length = "+$length";
    $hour = date(' H:i:s', $time);
    $day = date('d', $time);
    if ($day == '29' || $day == '30' || $day == '31') {
        // 目标年月
        $targetTime = strtotime(date('Y-m', $time) . " $length month");
        $targetYearMonth = date('Y-m-', $targetTime);
        // 目标月最后一天
        $targetLastDay = date('t', $targetTime);
        // 如果目标月最后一天大于等于 $day 则正常返回,否则返回目标月的最后一天
        if ($targetLastDay >= $day) $targetLastDay = $day;
        // 返回目标时间 格式:xxxx-xx-xx xx:xx:xx
        return $targetYearMonth . $targetLastDay . $hour;
    }
    return date('Y-m-d H:i:s', strtotime("$length month", $time));}