简体   繁体   中英

Substract time in Laravel

I have two fields beginning time and endingtime in a Mysql database. I want to calculate a duration inside a view in Laravel. So I wrote :

{{ $date1=date('G:i',strtotime($timeSlot->beginningTime)) }}
{{ $date2=date('G:i',strtotime($timeSlot->endingTime)) }}
{{ $date2-$date1 }}

My issue is : the difference gives me only hours difference without minutes...

Thanks for your help

You can use Carbon for that. Just tested, works perfectly:

$difference = Carbon::parse($timeSlot->beginningTime)->diff(Carbon::parse($timeSlot->endingTime));

In the view:

{{ $difference->h }}:{{ $difference->i }}

If you cast dates , you don't even need to parse:

$difference = $timeSlot->beginningTime->diff($timeSlot->endingTime);

It's bad practice to have logic inside a view.

Use carbon and pass data from a controller to the view.

$date1 = Carbon::parse(date('G:i',strtotime($timeSlot->beginningTime)));
$date2 = Carbon::parse(date('G:i',strtotime($timeSlot->endingTime)));

$totalDuration = $date1->diffInSeconds($date2);

Then use gmdate :

   $exactDuration =  gmdate('H:i:s', $totalDuration);

// 00:00:21

You can then pass this $exactDuration to your view and use it there.

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