如果我使用这个代码,我会得到奇怪的结果:
$datetime = new DateTime('2015-01-31');
$datetime->modify('+1 month');
echo $datetime->format('Y-m-t') . "<br>";
$datetime->modify('+1 month');
echo $datetime->format('Y-m-t') . "<br>";
$datetime->modify('+1 month');
echo $datetime->format('Y-m-t') . "<br>";
我得到这个:
2015-03-31
2015-04-30
2015-05-31
而不是2015-02-28
。
如何修复?
按照DateTime
的工作方式,+ 1 month
将月份值增加一,得到2015-02-31
。由于2月份只有28或29天,这将持续到3月的头几天。然后,正如你所知,索要Y-m-t
会给你三月的最后一天。
由于您已经使用t
来获取月的最后一天,因此可以通过以月初的日期开始来避免此问题:
$datetime = new DateTime('2015-01-01');
参考:PHP DateTime::修改加减月份
如果你想获得下个月的最后一天,你可以使用:
$datetime->modify('last day of next month');
您可以尝试此函数将月份添加到日期时间对象
/**
*
* @param DateTime $date DateTime object
* @param int $monthToAdd Months to add at time
*/
function addMonth(DateTime $date, $monthToAdd)
{
$year = $date->format('Y');
$month = $date->format('n');
$day = $date->format('d');
$year += floor($monthToAdd / 12);
$monthToAdd = $monthToAdd % 12;
$month += $monthToAdd;
if ($month > 12) {
$year ++;
$month = $month % 12;
if ($month === 0) {
$month = 12;
}
}
if (! checkdate($month, $day, $year)) {
$newDate = DateTime::createFromFormat('Y-n-j', $year . '-' . $month . '-1');
$newDate->modify('last day of');
} else {
$newDate = DateTime::createFromFormat('Y-n-d', $year . '-' . $month . '-' . $day);
}
$newDate->setTime($date->format('H'), $date->format('i'), $date->format('s'));
return $newDate->format('Y-m-d');
}
echo addMonth(new DateTime('2015-01-30'), 1); //2015-02-28
echo addMonth(new DateTime('2015-01-30'), 2); //2015-03-30
echo addMonth(new DateTime('2015-01-30'), 3); //2015-04-30
这样修复它。
$datetime = new DateTime('2015-01-31');
$datetime->modify('28 days');
echo $datetime->format('Y-m-t') . "<br>";
$datetime->modify('+1 month');
echo $datetime->format('Y-m-t') . "<br>";
$datetime->modify('+1 month');
echo $datetime->format('Y-m-t') . "<br>";
你会得到
2015-02-28
2015-03-31
2015-04-30