2016-05-11 197 views
16

我需要首先最后一天使用碳库,我曾尝试如下:上个月的:如何获得上月的第一天和最后一天与碳 - Laravel

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

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

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

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

回答

29

试试这个:

$start = new Carbon('first day of last month'); 
$end = new Carbon('last day of last month'); 
+0

太棒了,它完美的作品:)。谢谢 – Siddharth

+0

不客气@Siddharth。 –

+0

没有获得时间00:00:00 –

12

刚刚尝试这一点

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

+2

这绝对是最好的,因为它始于00:00,结束于23:59:59。接受的解决方案没有考虑到时间,可能会产生不可靠的结果。 – rgehan

2

在返回的使用方法

Carbon::now()->startOfMonth()->subMonth()->endOfMonth()->toDateTimeString(); 

的错误结果时,目前的碳中的错误最后一天为那些有31天的月份的30天。

IE浏览器 - 如果你是在3月份,并且运行上述调用,它将返回2017-03-30,而不是你所期望的2017-03-31。

当我在做我最后使用日期之间的操作..

Carbon::now()->startOfMonth()->subSeconds(1)->toDateTimeString(); 

这结束了正确的日期dateTimeString对于那些在31日的结束日。

2

这... ...在23:59

$start = new Carbon('first day of last month'); 
$start->startOfMonth(); 
$end = new Carbon('last day of last month'); 
$end->endOfMonth(); 
0

在00:00和日期结束结束日期开始初始化具体回答你的问题,为什么你得到错误的结果为$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. 

这给我们留下了一个无效的日期 - 没有月31日。多余的日期只需添加到最后一个有效日期(2016年4月30日+ 1),将日期推到5月(2016-05-01)。

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

$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 
相关问题