且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

碳 - 为什么addMonths()更改月的日子?

更新时间:2023-11-15 23:36:52

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



以下链接:



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



提供了在2012年3月31日之前添加1个月到2012年3月3日的示例。这是打算,虽然似乎令我困惑。



作为展示不同行为的反例,在SQL中:

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

29/2012,所以***检查你计划使用的addmonth()函数的规格。


Here's the simple example (today is 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.

Am I missing something about date modifications?

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

The following link:

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:

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.