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?
Solution 1:
Try this:
$start = new Carbon('first day of last month');
$end = new Carbon('last day of last month');
Solution 2:
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
Solution 3:
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();