碳按数字获取月份返回数字2 [英] Carbon get month by number returns march for number 2

查看:103
本文介绍了碳按数字获取月份返回数字2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前有没有人遇到此错误,或者知道一种解决方法?

Has anyone ever had this bug before, or know a way to fix it?

我想以数组的形式获取当年所有月份的列表(开始日期和结束日期),所以我正在这样做(接受更清洁更简便方法的建议)

I want to get a list of all months in the current year (start date and end date) in an array, so i'm doing like this (open to suggestions for cleaner easier ways)

//Create a months array
$months = [];
//Get start and end of all months
for($i = 1; $i <= 12; $i++){
   $array = [];
   $array['start'] = Carbon::create()->month($i)->startOfMonth()->format('d/m/y');
   $array['end'] = Carbon::create()->month($i)->endOfMonth()->format('d/m/y');
   array_push($months, $array);
}

哪个会产生此结果

如您所见,它循环并检索了月份,但请注意,它完全跳过了2月,并两次添加了3月.

As you can see, its looped and retrieved the months, but notice that it skips February completely and adds March twice.

如果我手动运行并返回此代码

If I manually run and return this code

return Carbon::create()->month(2)->startOfMonth()->format('d/m/y');

它返回01/03/2018.

为什么碳在第二个月的三月份打印出来?有没有人曾经遇到过这个问题或知道过解决方法?

Why does carbon print out March for month 2? Has anyone ever had this issue before or know of a way to fix it?

推荐答案

Carbon::create()->month(2)将首先创建今天的日期,然后将月份设置为 2 ,但保留其他值.由于今天的日期是8月29日,因此该日期最终以2月29日为基准,该日期(至少是今年)不存在. PHP将这些伪造"日期累积到下个月,因此 2月29日变为 3月1日.

Carbon::create()->month(2) will first create today's date, and then set the month to 2, but keep the other values. Because today's date is the 29th of August, the date ends up referring to the 29th of February, which (this year at least) doesn't exist. PHP rolls these "fake" dates over into the next month, so February 29th becomes March 1st.

如果您首先明确设置月份中的某天,则应该可以按预期运行:

If you explicitly set the day of the month first, this should work as expected:

Carbon::create()->day(1)->month($i);

(此外,如果您昨天尝试过此操作,它将很好用,并且您可能从未注意到过该错误.如果明天进行尝试,则可能会在3月2日结束,并且可能注意到它的速度要快得多.日期很好玩.)

(Also, if you'd tried this yesterday it would have worked fine, and you might never have noticed the bug. If you tried it tomorrow, you would have ended up with March 2nd and probably noticed it a lot faster. Dates are great fun.)

这篇关于碳按数字获取月份返回数字2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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