Carbon Difference in Time between two Dates in hh:mm:ss format

DateLaravelLaravel 5.1Php Carbon

Date Problem Overview


I'm trying to figure out how I can take two date time strings that are stored in our database and convert it to a difference in time format of hh:mm:ss.

I looked at diffForHumans, but that does give the format I'd like and returns things like after, ago, etc; which is useful, but not for what I'm trying to do.

The duration will never span days, only a max of a couple hours.

$startTime = Carbon::parse($this->start_time);
$finishTime = Carbon::parse($this->finish_time);

$totalDuration = $finishTime->diffForHumans($startTime);
dd($totalDuration);

// Have: "21 seconds after"
// Want: 00:00:21

Date Solutions


Solution 1 - Date

I ended up grabbing the total seconds difference using Carbon:

$totalDuration = $finishTime->diffInSeconds($startTime);
// 21

Then used gmdate:

gmdate('H:i:s', $totalDuration);
// 00:00:21

If anyone has a better way I'd be interested. Otherwise this works.

Solution 2 - Date

$finishTime->diff($startTime)->format('%H:%I:%S');
// 00:00:21

Solution 3 - Date

$start  = new Carbon('2018-10-04 15:00:03');
$end    = new Carbon('2018-10-05 17:00:09');

You may use

$start->diff($end)->format('%H:%I:%S');

which gives the difference modulo 24h

>02:00:06

If you want to have the difference with more than 24h, you may use :

$start->diffInHours($end) . ':' . $start->diff($end)->format('%I:%S');

which gives :

>26:00:06

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmtpultzView Question on Stackoverflow
Solution 1 - DatemtpultzView Answer on Stackoverflow
Solution 2 - DateSTWilsonView Answer on Stackoverflow
Solution 3 - DateAdamView Answer on Stackoverflow