简体   繁体   中英

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?

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:

Carbon\CarbonImmutable @1630454400 {#5430
    date: 2021-09-01 00:00:00.0 UTC (+00:00),
}

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM