php Carbon - 为什么 addMonths() 改变月份中的某一天?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39207798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:49:57  来源:igfitidea点击:

Carbon - why addMonths() change the day of month?

phplaraveldatedatetimephp-carbon

提问by Limon Monte

Here's the simple example (today is 2016-08-29):

这是一个简单的例子(今天是 2016-08-29):

var_dump(Carbon::now());
var_dump(Carbon::now()->addMonths(6));

Output:

输出:

object(Carbon\Carbon)#303 (3) {
  ["date"] => string(26) "2016-08-29 15:37:11.000000"
}
object(Carbon\Carbon)#303 (3) {
  ["date"] => string(26) "2017-03-01 15:37:11.000000"
}

For Carbon::now()->addMonths(6)I'm expecting 2017-02-29, not 2017-03-01.

因为Carbon::now()->addMonths(6)我在期待2017-02-29,而不是2017-03-01

Am I missing something about date modifications?

我是否缺少有关日期修改的信息?

回答by RIanGillis

There is no 2/29/2017. Leap-year happened in 2016.

没有 2/29/2017。闰年发生在 2016 年。

The following link:

以下链接:

http://carbon.nesbot.com/docs/#api-addsub

http://carbon.nesbot.com/docs/#api-addsub

provides an example of adding 1 month to 1/31/2012 and arriving on 3/3/2012. Which is intended, though seems confusing to me.


As a counter-example exhibiting different behavior, in SQL:

提供了将 1 个月添加到 2012 年 1 月 31 日并于 2012 年 3 月 3 日到达的示例。这是有意的,尽管对我来说似乎很困惑。


作为表现出不同行为的反例,在 SQL 中:

SELECT dateadd(m,1,'2012-01-31') 

results in 2/29/2012, so it would be a good idea to check the specifications of whatever addmonth() function you plan on using.

结果是 2/29/2012,因此检查您计划使用的任何 addmonth() 函数的规格是个好主意。

回答by Alexander Malakhov

It's even more crippled than that - subtraction has same issues. There are special methods to avoid overflows, though:

它甚至比那更残缺 - 减法也有同样的问题。不过,有一些特殊的方法可以避免溢出:

function original(){ 
    return new Carbon('2016-08-31'); 
};
function print_dt($name, $date){ 
    echo $name . $date->toAtomString() . PHP_EOL; 
};

print_dt('original:            ', original());
echo '-----' . PHP_EOL;
print_dt('addMonths:           ', original()->addMonths(6));
print_dt('addMonthsNoOverflow: ', original()->addMonthsNoOverflow(6));
echo '-----' . PHP_EOL;
print_dt('subMonths:           ', original()->subMonths(2));
print_dt('subMonthsNoOverflow: ', original()->subMonthsNoOverflow(2));

output:

输出:

original:            2016-08-31T00:00:00+00:00
----- 
addMonths:           2017-03-03T00:00:00+00:00
addMonthsNoOverflow: 2017-02-28T00:00:00+00:00
----- 
subMonths:           2016-07-01T00:00:00+00:00
subMonthsNoOverflow: 2016-06-30T00:00:00+00:00