Search code examples
phplaraveldatephp-carbon

Carbon format only years and days with leap year


I'm trying to get diff between 2 dates but only with years and days but adding months to days, example:

$date1 = \Carbon\Carbon::parse(02.02.2021); 
$date2 = \Carbon\Carbon::parse(01.01.2000);
$date2->diff($date1)->format('Y d');

But if I use format without month, it will be omitted and won't be added to days.

21 years, 1 day

But real is

21 years, 1 month, 1 day

So I want for example

21 years, 32 days

So I did:

$days = $date2->diffInDays($date1)
$years = intval($days/ 365);
$days_minusYears = $days % 365;

$diff = "$years"."y"." $days_minusYears"."d",

Unfortunately It will skip leap years. How to do It properly?


Solution

  • check this out

    $date1 = Carbon::parse("02.02.2021");
    $date2 = Carbon::parse("01.01.2000");
    

    First get difference of years between 2 dates

    $y = $date2->diff($date1)->y;
            
    

    once you get years add those years so you will have 2 dates of current year, and when you get difference of days of current year using Carbon, you will get correct days

     $date3= $date2->addYears($y);       
     
    

    Complete code

        $date1 = Carbon::parse("02.02.2021");
        $date2 = Carbon::parse("01.01.2000");
        
        $years_total = $date2->diff($date1)->y;
        $date3= $date2->addYears($years_total); //2021-01-01 using above example
        $days_excluding_years = ($date3->diff($date1)->days);
        echo $years_total ." Years ". $days_excluding_years ." days";