从年初开始获取前几个月的列表
我正在尝试使用碳
获取前几个月的列表。
预期结果:
January, February, March, April
到目前为止所做的事情:
$now = Carbon::now();
$startMonth = $now->startOfMonth()->subMonth($now->month);
$currentMonth = $now->startOfMonth();
$diff = $currentMonth->diffInMonths($startMonth);
我使用Carbon :: Now()()
获得了一年中的第一个月,然后我尝试计算日期之间的差异,但我得到了0
。
同样,我也会找到任何将月份列表作为预期产出的列表的方法。
I'm trying to get a list of previous months using Carbon
.
Expected result:
January, February, March, April
What I did so far:
$now = Carbon::now();
$startMonth = $now->startOfMonth()->subMonth($now->month);
$currentMonth = $now->startOfMonth();
$diff = $currentMonth->diffInMonths($startMonth);
I've used Carbon::now()
to get the first month of the year, then I tried to calculate the difference between the dates but I got 0
.
Also I canno find any method that returns a list of months as the expected output.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不一个简单的
循环?
$ preathths
现在是:编辑
如果需要相反的顺序,则
,然后:然后
$ preathsmonths
将是:Why not a simple
while
loop?$previousMonths
would now be:Edit
If you need them in the opposite order, then:
Then
$previousMonths
will be:您将原始变量设置为上一年的12月1日,因为您不断修改原始变量而不是复制它。相反,创建两个变量,从
now()
中创建两个变量,然后您可以使用它来创建Carbonperiod以迭代。You're setting the original variable to December 1st of the previous year, since you keep modifying the original instead of copying it. Instead, create two variables off of
now()
, then you can use that to create a CarbonPeriod to iterate through.使用PHP范围的另一种方法:
从一月到本月(类似于预期的结果),这应该返回几个月的收集(如果使用Toarray()的数组)
Another approach using PHP range:
This should return a collection of months (array if toArray() is used) from January until the current month (similar to the expected result)