Home > Mobile >  How to calculate difference between two dates as day month year using carbon in laravel
How to calculate difference between two dates as day month year using carbon in laravel

Time:02-23

I want to calculate difference between two dates as day,month and year.

What I did :

$year = Carbon::now()->diffInYears($row->entry_date);
$month = Carbon::now()->diffInMonths($row->entry_date);
$day = Carbon::now()->diffInDays($row->entry_date);
$month = $month > 12 ? $month-(12*$year) : $month;
$day = $day>30 ? $day-((365*$year) ($month*30)) : $day;
return '<td>' . $year . ' Year ' . $month . ' Month ' . $day . ' Day ' . '</td>';

when i do it this way i am calculating wrong. Is there a method in Carbon to calculate this correctly?

CodePudding user response:

You may use some logic like this:

$entry_date = Carbon::parse("1992-05-18 00:00:00");

$year   = Carbon::now()->diffInYears($entry_date);
$entry_date->addYears($year);
$month  = Carbon::now()->diffInMonths($entry_date);
$entry_date->addMonths($month);
$day    = Carbon::now()->diffInDays($entry_date);

return '<td>' . $year . ' Year ' . $month . ' Month ' . $day . ' Day ' . '</td>';

CodePudding user response:

you can use this but adjust according to your own code

public function validationDays_remaining($date){
    
    $valid_date = Carbon::parse($date)->toDateString();
    $valid_date = date('Y.m.d\\TH:i', strtotime($valid_date));
    $today = new \DateTime();
    $today->setTime(0, 0, 0);

    $match_date = \DateTime::createFromFormat("Y.m.d\\TH:i", $valid_date);
    $match_date->setTime(0, 0, 0);

    $diff = $today->diff($match_date);
    $diffDays = (integer)$diff->format("%R%a");
    
    return $diffDays;

}

CodePudding user response:

$seconds =  Carbon::now()->diffSeconds($row->entry_date);
CarbonInterval::seconds($seconds)->cascade()->forHumans();

CodePudding user response:

I found a short and simple way

$time = Carbon::now()->diff($row->entry_date);
return '<td>' . $time->y . ' Year' . $time->m . ' Month' . $time->d . ' Day' . '</td>';
  • Related