laravel hh:mm:ss 格式的两个日期之间的碳时间差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33575239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Carbon Difference in Time between two Dates in hh:mm:ss format
提问by mtpultz
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.
我试图弄清楚如何获取存储在我们数据库中的两个日期时间字符串并将其转换为 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.
我查看了diffForHumans
,但这确实提供了我想要的格式并返回诸如after
, 之类的内容ago
;这很有用,但不适用于我正在尝试做的事情。
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
回答by mtpultz
I ended up grabbing the total seconds difference using Carbon:
我最终使用 Carbon 获取了总秒数差异:
$totalDuration = $finishTime->diffInSeconds($startTime);
// 21
Then used gmdate
:
然后使用gmdate
:
gmdate('H:i:s', $totalDuration);
// 00:00:21
If anyone has a better way I'd be interested. Otherwise this works.
如果有人有更好的方法,我会感兴趣。否则这有效。
回答by STWilson
$finishTime->diff($startTime)->format('%H:%I:%S');
// 00:00:21
回答by Adam
$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
这给出了模 24h 的差值
02:00:06
02:00:06
If you want to have the difference with more than 24h, you may use :
如果你想有超过 24 小时的差异,你可以使用:
$start->diffInHours($end) . ':' . $start->diff($end)->format('%I:%S');
which gives :
这使 :
26:00:06
26:00:06