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 协议》,转载必须注明作者和本文链接
我按照你的思路重新写了一个,你瞧瞧呢:
Carbon香不香 加1月不超出