PHP Carbon DateTime增加了两个月,完全跳过十一月 [英] PHP Carbon DateTime adds two months and skips november entirely

查看:757
本文介绍了PHP Carbon DateTime增加了两个月,完全跳过十一月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要显示三个日历,一个是当月,另一个是两个月。



我正在使用Carbon进行这些计算。 p>

今天是10月31日。



如果我写下面的

  $ carbon = Carbon :: now('UTC'); // UTC的当前日期时间是2016年10月31日上午8:54 
echo $ carbon->格式('F')。 '< br>';
echo $ carbon-> addMonths(1) - >格式('F');

我得到这个输出


十月



十二月


...所以如何在十月份增加一个月,这样我就能到11月份。

解决方案

默认情况下 addMonths(1)正好添加了30天月。



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



所以例如:

  $ carbon = Carbon :: now('UTC'); // UTC的当前日期时间是2016年10月31日上午8:54 
echo $ carbon->格式('F')。 '< br>';
echo $ carbon-> addMonths(1) - >格式('F');

意外输出:



十月
十二月



  $ carbon = Carbon :: now('UTC'); // UTC的当前日期时间是2016年10月31日上午8:54 
echo $ carbon->格式('F')。 '< br>';
echo $ carbon-> addMonthsNoOverflow(1) - > format('F');

正确输出:



10月11日



此行为不是由于Carbon而是由于基于PHP日期时间类建立的。



原因 addMonthsNoOverflow()不是默认的行为是因为这将是一个打破变化。不幸的是,这在文档中没有提及,所以-1指向碳。



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


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.

解决方案

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'. Unfortunately this is NOT mentioned in the documentation either so -1 points to carbon for that.

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

这篇关于PHP Carbon DateTime增加了两个月,完全跳过十一月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆