Search code examples
phplaravelphp-carbon

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?


Solution

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