两个日期之间的碳时间差异 hh: mm: ss 格式

我正试图找出如何将存储在数据库中的两个日期时间字符串转换为 hh: mm: ss 的时间格式差异。

我查看了 diffForHumans,但它确实给出了我想要的格式,并返回诸如 afterago等内容; 这很有用,但不适用于我正在尝试做的事情。

持续时间不会超过几天,最多几个小时。

$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
154800 次浏览

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.

$finishTime->diff($startTime)->format('%H:%I:%S');
// 00:00:21
$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

I know this is an old question, but it still tops Google results when searching for this sort of thing and Carbon has added a lot of flexibility on this, so wanted to drop a 2022 solution here as well.

TL;DR - check out the documentation for different/more verbose versions of the ABC0 method, and greater control over options.

As an example, we needed to show the difference between two Carbon instances (start and end) in hours & minutes, but it's possible they're more than 24 hours apart—in which case the minutes become less valuable/important. We want to exclude the "ago" or Also wanted to join the strings with a comma.

We can accomplish all of that, with the $options passed into diffForHumans, like this:

use Carbon\CarbonInterface;


$options = [
'join' => ', ',
'parts' => 2,
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
];


return $end->diffForHumans($start, $options);

Which will result in values like what's seen in the Duration column:

Hope that's helpful for someone!

You can do it using the Carbon package this way to get the time difference:

$start_time = new Carbon('14:53:00');
$end_time = new Carbon('15:00:00');
$time_difference_in_minutes = $end_time->diffInMinutes($start_time);//you also find difference in hours using diffInHours()