我正在创建一个时间表,以显示预期和实际时间。
持续时间如下保存
23:15
-23小时15分钟
25:45
-25小时45分钟
我需要计算两者之间的小时和分钟数差异(额外工作时间)
我已经尝试了以下
$acutal=='23:15';
$expected=='25:45';
$start_time = new DateTime("1970-01-01 $acutal:00");
$time = $start_date->diff(new DateTime("1970-01-01 $expected:00"));
确实可以,但是当工作时间超过24:00时,会引发错误(显然是因为它正在读取时间)
消息为'DateTime :: __ construct()的未捕获异常'Exception':无法解析时间字符串(1970-01-01 25:45:00)
还有另一种方法吗?
您可以检查小时数是否大于24,如果是,则增加一天并删除24小时。
$actual='23:15';
$expected='25:45';
$day = 1;
list($hrs, $min) = explode(':', $expected);
if ($hrs > 24) { $day += 1; $hrs -= 24; }
$start_time = new DateTime("1970-01-01 $actual:00");
$time = $start_time->diff(new DateTime("1970-01-$day $hrs:$min:00"));
echo $time->format('%hh %Im');
输出:
2h 30m
另请注意,该==
用于比较而不是分配。
如果有48小时或更长时间,也可以更改if ($hrs > 24)
by while()
。
编辑
如@CollinD所指出的,如果时间超过一个月的天数,它将失败。这是另一种解决方案:
$actual='23:15';
$expected='25:45';
list($hrs, $min) = explode(':', $actual);
$total1 = $min + $hrs * 60;
list($hrs, $min) = explode(':', $expected);
$diff = $min + $hrs * 60 - $total1;
$start_time = new DateTime();
$expected_time = new DateTime();
$expected_time->modify("+ $diff minutes");
$time = $start_time->diff($expected_time);
echo $time->format('%hh %Im');
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句