PHP计算两个时间戳间每日耗时的问题排查
每日时间戳耗时统计问题修复
问题根源
- 缺失结束日期记录:原循环逻辑未覆盖「结束时间小时数小于开始时间」的场景,导致结束日期当天的耗时统计被跳过。
- 分钟数偏差:原计算未对秒数转分钟做取整处理,5秒的差值导致结果显示为554.9分钟,而非预期的555分钟。
修复方案
核心思路
- 遍历从开始日期到结束日期的所有日期(含首尾),逐个计算每日有效耗时:
- 首日:统计从起始时间到当日23:59:59的时长
- 末日:统计从当日00:00:00到结束时间的时长
- 中间日期:直接按全天24小时(1440分钟)计算
- 对秒数转分钟的结果做取整,消除精度偏差
代码实现(PHP)
<?php $startTimestamp = "2023-08-05 14:45:05"; $endTimestamp = "2023-08-09 12:00:14"; // 转为DateTime对象,简化日期操作 $start = new DateTime($startTimestamp); $end = new DateTime($endTimestamp); $currentDate = clone $start; $currentDate->setTime(0, 0, 0); // 定位到当日零点 $endDate = clone $end; $endDate->setTime(0, 0, 0); $dailyDurations = []; // 循环覆盖所有日期(含开始/结束日) while ($currentDate <= $endDate) { $dateStr = $currentDate->format('Y-m-d'); if ($currentDate == $start->setTime(0,0,0)) { // 计算首日耗时:从起始时间到当日23:59:59 $dayEnd = clone $currentDate; $dayEnd->setTime(23, 59, 59); $diff = $dayEnd->diff($start); $minutes = $diff->h * 60 + $diff->i + round($diff->s / 60); } elseif ($currentDate == $endDate) { // 计算末日耗时:从当日零点到结束时间 $dayStart = clone $currentDate; $diff = $end->diff($dayStart); $minutes = $diff->h * 60 + $diff->i + round($diff->s / 60); } else { // 中间日期按全天1440分钟计算 $minutes = 1440; } $dailyDurations[$dateStr] = "{$minutes}分钟"; $currentDate->add(new DateInterval('P1D')); // 日期加1天 } // 输出结果 print_r($dailyDurations); ?>
验证结果
执行后将得到5天的统计数据:
2023-08-05: 555分钟2023-08-06: 1440分钟2023-08-07: 1440分钟2023-08-08: 1440分钟2023-08-09: 720分钟
内容的提问来源于stack exchange,提问作者Mr Cathode
相关产品推荐
相关产品推荐

