Reputation: 54
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?
Upvotes: 0
Views: 6312
Reputation: 4412
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');
Upvotes: 2
Reputation: 3847
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),
}
Upvotes: 4