PHP Carbon DateTime 增加了两个月并完全跳过了 11 月
PHP Carbon DateTime adds two months and skips november entirely
我需要显示三个日历,一个用于当月,另外两个用于接下来的两个月。
我正在使用 Carbon 进行这些计算。
今天是 10 月 31 日。
如果我这样写
$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');
我得到这个输出
October
December
我完全错过了 11 月...那么如何在 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 月
十二月
鉴于
$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 日期时间 class。
addMonthsNoOverflow()
不是默认行为的原因是因为这将是 'breaking change'。
您可以在这个 Github 对话中阅读更多相关信息:https://github.com/briannesbitt/Carbon/issues/627
这是 php 基础库中的一个错误:\DateTime
在您的 php 启动代码集中:
Carbon:: useMonthsOverflow(false);
要解决此问题,只能使用 addMonths()
。
警告,尽管这可能会破坏依赖于 Carbon 的现有代码(如果有的话)。
我需要显示三个日历,一个用于当月,另外两个用于接下来的两个月。
我正在使用 Carbon 进行这些计算。
今天是 10 月 31 日。
如果我这样写
$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');
我得到这个输出
October
December
我完全错过了 11 月...那么如何在 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 月 十二月
鉴于
$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 日期时间 class。
addMonthsNoOverflow()
不是默认行为的原因是因为这将是 'breaking change'。
您可以在这个 Github 对话中阅读更多相关信息:https://github.com/briannesbitt/Carbon/issues/627
这是 php 基础库中的一个错误:\DateTime
在您的 php 启动代码集中:
Carbon:: useMonthsOverflow(false);
要解决此问题,只能使用 addMonths()
。
警告,尽管这可能会破坏依赖于 Carbon 的现有代码(如果有的话)。