Search code examples
phplaraveldatephp-carbon

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

  • Try this:

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