Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get First and Last Day of Previous Month with Carbon - Laravel

I need First and Last Day of Previous Month using Carbon Library, what I have tried is as follows:

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

Result I'm getting is for$firstDayofPreviousMonth = '2016-04-01'(as current month is 5th(May)) and for $lastDayofPreviousMonth = '2016-05-01'.

I'm getting correct result for $firstDayofPreviousMonth, but it's giving me 30 days previous result, and giving me wrong result for $lastDayofPreviousMonth.

Can anyone help me out with this?

like image 600
Siddharth Avatar asked May 11 '16 05:05

Siddharth


People also ask

What does Carbon :: now () return?

Carbon::now returns the current date and time and Carbon:today returns the current date. This is a sample output.


4 Answers

Try this:

$start = new Carbon('first day of last month');
$end = new Carbon('last day of last month');
like image 191
Deniz B. Avatar answered Oct 17 '22 21:10

Deniz B.


Just try this

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

Updated code, which is more accurate

$firstDayofPreviousMonth = Carbon::now()->startOfMonth()->subMonthsNoOverflow()->toDateString();

$lastDayofPreviousMonth = Carbon::now()->subMonthsNoOverflow()->endOfMonth()->toDateString();

@kenfai Thanks

like image 31
Abu Sayem Avatar answered Oct 17 '22 21:10

Abu Sayem


With this ... the date start init on 00:00 and date end finish in 23:59

$start = new Carbon('first day of last month');
$start->startOfMonth();
$end = new Carbon('last day of last month');
$end->endOfMonth();
like image 17
sadalsuud Avatar answered Oct 17 '22 19:10

sadalsuud


To specifically answer your question as to why you're getting the wrong result for $lastDayofPreviousMonth.

Lets break down this statement in your example:

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

This leaves us with an invalid date — there is no 31st of April. The extra day is simply added on to the last valid date (2016-04-30 + 1) which rolls the date into May (2016-05-01).

As previously mentioned to be sure this never happens always reset the date to the 1st of the month before doing anything else (as every month has a 1st day).

$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
like image 12
Tama Avatar answered Oct 17 '22 20:10

Tama