PHP Carbon DateTime增加了两个月,并完全跳过了11月


PHP Carbon DateTime adds two months and skips november entirely

我需要显示三个日历,一个是当前月份的日历,另外两个是未来两个月的日历。

我用Carbon来做这些计算。

今天是十月三十一日。

如果我写下面的

$carbon = Carbon::now('UTC'); // current datetime in UTC is 8:54 AM October 31, 2016
echo $carbon->format('F') . '<br>';
echo $carbon->addMonths(1)->format('F');
我得到这个输出
10月

12月
我完全错过了十一月…我要怎么在10月上加一个月变成11月呢?

默认情况下,addMonths(1)恰好为一个月增加30天。

要精确地增加一个月(例如,从10月到11月,无论它是29/30/31天),您需要取消addMonth(),而使用addMonthsNoOverflow(n)

例如:

$carbon = Carbon::now('UTC'); // current datetime in UTC is 8:54 AM October 31, 2016
echo $carbon->format('F') . '<br>';
echo $carbon->addMonths(1)->format('F');

竟然输出:10月

12月

$carbon = Carbon::now('UTC'); // current datetime in UTC is 8:54 AM October 31, 2016
echo $carbon->format('F') . '<br>';
echo $carbon->addMonthsNoOverflow(1)->format('F');

正确输出:10月11月

这个行为不是由于Carbon,而是由于它所基于的PHP datetime类。

addMonthsNoOverflow()不是默认行为的原因是因为这将是一个"破坏性更改"。

你可以在这个Github对话中阅读更多信息:https://github.com/briannesbitt/Carbon/issues/627

这是一个错误的php基库:'DateTime

在你的PHP启动代码集:

Carbon:: useMonthsOverflow(false);

解决这个问题,只是能够使用addMonths()代替。

警告,虽然这可能会破坏现有的代码依赖于碳,如果你有任何。