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

Siddharth picture Siddharth · May 11, 2016 · Viewed 64.4k times · Source

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?

Answer

Deniz B. picture Deniz B. · May 11, 2016

Try this:

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