Laravel 8中按ID计算启停时段累计总耗时的实现问题
Laravel 8 计时总耗时统计实现方案
首先默认你已经将时间节点存储到了数据库,以下实现兼容两种常见的表结构设计,可根据你的实际情况选择:
方案A:时间节点存为同一记录的四个字段
如果你的表结构是单条计时记录对应四个时间字段(start_time/pause_time/resume_time/stop_time),直接用Laravel自带的Carbon类计算即可:
// 按ID查询对应记录 $timing = \App\Models\Timing::find($targetId); // 分段计算间隔 $firstDuration = \Carbon\Carbon::parse($timing->pause_time) ->diffInSeconds(\Carbon\Carbon::parse($timing->start_time)); $secondDuration = \Carbon\Carbon::parse($timing->stop_time) ->diffInSeconds(\Carbon\Carbon::parse($timing->resume_time)); // 总耗时(单位:秒) $totalSeconds = $firstDuration + $secondDuration;
方案B:每个时间节点存为独立行记录
如果你的表结构是每个操作对应一条记录(字段含type标识操作类型:start/pause/resume/stop、event_time存储时间、relation_id关联业务ID),兼容多次暂停/恢复的场景:
// 按业务ID拉取所有时间节点,按时间升序排列 $timeNodes = \App\Models\TimingNode::where('relation_id', $targetId) ->orderBy('event_time', 'asc') ->get(['type', 'event_time']); $totalSeconds = 0; $tempStartTime = null; foreach ($timeNodes as $node) { $eventTime = \Carbon\Carbon::parse($node->event_time); switch ($node->type) { case 'start': case 'resume': $tempStartTime = $eventTime; break; case 'pause': case 'stop': if ($tempStartTime) { $totalSeconds += $eventTime->diffInSeconds($tempStartTime); $tempStartTime = null; } break; } }
格式化总耗时(可选)
如果需要把总秒数转成时分秒格式展示,可直接使用Carbon的格式化方法:
$totalDuration = gmdate('H:i:s', $totalSeconds);
示例数据验证结果
你给出的示例时间代入计算后:
- 开始到暂停间隔:11分钟 = 660秒
- 恢复到停止间隔:6分钟 = 360秒
- 总耗时:1020秒 = 17分钟,格式化结果为
00:17:00
内容的提问来源于stack exchange,提问作者sneha bharathi
相关产品推荐
相关产品推荐

