如何使用Carbon - Laravel获得上个月的第一天和最后一天

Sid*_*rth 33 php date laravel php-carbon

我需要首先最后一天前一个月使用的碳库,我曾尝试如下:

$firstDayofPreviousMonth = Carbon::now()->startOfMonth()->subMonth()->toDateString();
$lastDayofPreviousMonth = Carbon::now()->endOfMonth()->subMonth()->toDateString();
Run Code Online (Sandbox Code Playgroud)

我得到的结果是$firstDayofPreviousMonth = '2016-04-01'(当前月份是第5(5月))和$lastDayofPreviousMonth = '2016-05-01'.

我得到了正确的结果$firstDayofPreviousMonth,但它给了我30天的结果,并给了我错误的结果$lastDayofPreviousMonth.

任何人都可以帮我解决这个问题吗?

Den*_* B. 52

试试这个:

$start = new Carbon('first day of last month');
$end = new Carbon('last day of last month');
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案。您还可以与 `endOfDay()` 或 `startOfDay()` 结合使用以获得 23:59:59 或 00:00:00 (3认同)
  • 未获取时间 00:00:00 (2认同)
  • 我不管你怎么想,既然问了这个,他也不知道该怎么办。所以多亏了你,他可能过滤了错误的东西。 (2认同)

Abu*_*yem 36

试试吧

$firstDayofPreviousMonth = Carbon::now()->startOfMonth()->subMonth()->toDateString(); $lastDayofPreviousMonth = Carbon::now()->subMonth()->endOfMonth()->toDateString();

  • 这绝对是最好的,因为它从00:00开始,到23:59:59结束.接受的解决方案不需要花费时间并且可能产生不可靠的结果. (3认同)

sad*_*uud 10

有了这个......日期从00:00开始初始化,日期结束于23:59结束

$start = new Carbon('first day of last month');
$start->startOfMonth();
$end = new Carbon('last day of last month');
$end->endOfMonth();
Run Code Online (Sandbox Code Playgroud)


Tam*_*ama 8

专门回答你的问题,为什么你得到了错误的结果$lastDayofPreviousMonth.

让我们在你的例子中分解这个陈述:

Carbon::now()->endOfMonth()->subMonth()->toDateString();
// Carbon::now() > 2016-05-05
// ->endOfMonth() > 2016-05-31
// ->subMonth() > 2016-04-31 // Simply takes 1 away from 5.
Run Code Online (Sandbox Code Playgroud)

这给我们留下了无效的日期 - 没有4月31日.额外的一天只是添加到最后一个有效日期(2016-04-30 + 1),该日期将日期滚动到五月(2016-05-01).

如前所述,确保这种情况永远不会发生,总是将日期重置为月份的第1天,然后再做其他事情(因为每个月都有第1天).

$lastDayofPreviousMonth = Carbon::now()->startofMonth()->subMonth()->endOfMonth()->toDateString();
// Carbon::now() > 2016-05-05
// ->startofMonth() > 2016-05-01 00:00:00
// ->subMonth() > 2016-04-01 00:00:00
// ->endOfMonth() > 2016-04-30 23:59:59
Run Code Online (Sandbox Code Playgroud)


小智 5

目前Carbon在使用该方法时存在一个错误

Carbon::now()->startOfMonth()->subMonth()->endOfMonth()->toDateTimeString();
Run Code Online (Sandbox Code Playgroud)

该错误导致对于有 31 天的月份,最后一天返回为 30。

IE - 如果您在 3 月份运行上述调用,它将返回 2017-03-30,而不是您期望的 2017-03-31。

当我在日期之间进行操作时,我最终使用了..

Carbon::now()->startOfMonth()->subSeconds(1)->toDateTimeString();
Run Code Online (Sandbox Code Playgroud)

最终得到 31 日结束的正确日期 dateTimeString。


小智 5

另一种解决方案是使用 Carbon 方法subMonthNoOverflow()

$lastDayofPreviousMonth = Carbon::now()->subMonthNoOverflow()->endOfMonth()->toDateString();
Run Code Online (Sandbox Code Playgroud)

当遇到每月 31 天的问题时在这里找到它:https ://github.com/briannesbitt/Carbon/issues/627