PHP给定时间戳加减月份操作

PHP下给定时间戳,加/减多少月,当在29、30、31号的时候,直接使用strtotime(‘+1 month’)会出现错误,所以需要处理时间。

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));
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
八度余溫。
讨论数量: 4

我按照你的思路重新写了一个,你瞧瞧呢:

/**
 * 获取几个月之后的最后时间
 *
 * @param int $time 这里默认就是传入的是时间戳
 * @param int $length 这里传入的是增加的月份
 * @return string
 */
function setDate(int $time, int $length): string
{
    $datetime = new DateTimeImmutable();
    $datetime = $datetime->setTimestamp($time);

    return $datetime->setDate($datetime->format('Y'), $datetime->format('n'), 1)
        ->add(new DateInterval("P{$length}M"))
        ->format('Y-m-t H:i:s');
}
1年前 评论
# 这个没有问题,看下鸟哥的 https://www.laruence.com/2018/07/31/3207.html
echo date('Y-m', strtotime("first day of +1 months"));
1年前 评论
now()->addMonthsNoOverflow(1)

Carbon香不香 加1月不超出

1年前 评论
小李世界 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!