get last month and year using carbon laravel

This might be a simple, I’ve $month and $year, but I’m trying to get lastMonthYear and lastToLastMonthYear.

    $date = Carbon::create($year, $month)->startOfMonth();

    $sameMonthLastYear = $date->subYear()->format('Ym');
    $lastMonthYear =  $date->subMonth()->format('Ym');
    $LastToLastMonthYear = $date->subMonth()->format('Ym');

Considering $month=9 and $year=2021, I’m trying to get
sameMonthLastYear = 202009
lastMonthYear = 202108
lastToLastMonthYear = 202107

but I’m getting
sameMonthLastYear = 202009
lastMonthYear = 202008
lastToLastMonthYear = 202008

Because $date value is keep updating for every line. Is there any way to get the expected result?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The right way is to use CarbonImmutable:

$date = CarbonImmutable::create($year, $month);

$sameMonthLastYear = $date->subYear()->format('Ym'); //202009
$lastMonthYear =  $date->subMonth()->format('Ym'); //202108
$LastToLastMonthYear = $date->subMonths(2)->format('Ym'); //202107

With CarbonImmutable, the changes you make to $date are not persisted.

I also removed the startOfMonth method, it was useless since by default, the Carbon instance will be:

CarbonCarbonImmutable @1630454400 {#5430
    date: 2021-09-01 00:00:00.0 UTC (+00:00),

Method 2

You can use copy() method:

$date = Carbon::create($year, $month)->startOfMonth();

$sameMonthLastYear = $date->copy()->subYear()->format('Ym');
$lastMonthYear =  $date->copy()->subMonth()->format('Ym');
$LastToLastMonthYear = $date->copy()->subMonths(2)->format('Ym');

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x