PHP Carbon DateTime adds two months and skips november entirely

◇◆丶佛笑我妖孽 提交于 2019-12-10 22:49:26

问题


I need to display three calendars one for the current month and the other two for the next two months.

I am using Carbon to do these calculations.

Today is the 31st of October.

If I write the following

$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');

I get this output

October

December

I am completely missing November... so how do I add a month on to October so that I get November.


回答1:


By default addMonths(1) adds exactly 30 days to a month.

To add exactly one month (e.g. to go from October to November regardless of whether it is 29/30/31 days) you need to do away with addMonth() and instead use addMonthsNoOverflow(n).

So for example:

$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');

unexpectedly Outputs:

October December

Whereas

$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');

Correctly outputs:

October November

This behaviour is not due to Carbon but due to the PHP datetime class that it is built on.

The reason addMonthsNoOverflow() is NOT the default behaviour is because this would be a 'breaking change'.

You can read more about it in this Github conversation: https://github.com/briannesbitt/Carbon/issues/627




回答2:


It's an error in php base lib: \DateTime

in your php startup code set:

Carbon:: useMonthsOverflow(false);

To fix this issue and just be able to use addMonths() instead.

Warning though this might break existing code that depends on Carbon, if you had any.



来源:https://stackoverflow.com/questions/40339101/php-carbon-datetime-adds-two-months-and-skips-november-entirely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!