Php 计算总小时数
在php中,给定字符串格式的时间,如何添加超过24小时的小时、分钟和秒? 前 结果是:Php 计算总小时数,php,Php,在php中,给定字符串格式的时间,如何添加超过24小时的小时、分钟和秒? 前 结果是: “34:00:15”您将无法使用典型的日期类(如DateTime)或函数(如date())来输出超过24小时的时间。因此,您必须手动执行此操作 首先,您需要将时间设置为秒,以便轻松地将它们相加。您可以使用explode功能获取小时、分钟和秒数,并将这些值乘以所需秒数。(60秒等于1分钟。60*60秒等于1小时) 然后需要输出小时、分钟和秒的总数。这可以通过除法(同样,1小时是60*60秒,因此将秒数除以60*
“34:00:15”您将无法使用典型的日期类(如
DateTime
)或函数(如date()
)来输出超过24小时的时间。因此,您必须手动执行此操作
首先,您需要将时间设置为秒,以便轻松地将它们相加。您可以使用explode
功能获取小时、分钟和秒数,并将这些值乘以所需秒数。(60秒等于1分钟。60*60秒等于1小时)
然后需要输出小时、分钟和秒的总数。这可以通过除法(同样,1小时是60*60秒,因此将秒数除以60*60得到小时)和模数运算符(%
)得到分和秒的“余数”,非常容易实现
<?php
// Starting values
$time1 = "10:50:00";
$time2 = "24:00:15";
// First, get the times into seconds
$time1 = explode(":", $time1);
$time1 = $time1[0] * (60*60) // Hours to seconds
+ $time1[1] * (60) // Minutes to seconds
+ $time1[2]; // Seconds
$time2 = explode(":", $time2);
$time2 = $time2[0] * (60*60) // Hours to seconds
+ $time2[1] * (60) // Minutes to seconds
+ $time2[2]; // Seconds
// Add the seconds together to get the total number of seconds
$total_time = $time1 + $time2;
// Now the "tricky" part: Output it in the hh:mm:ss format.
// Use modulo to determine the hours, minutes, and seconds.
// Don't forget to round when dividing.
print
//Hours
floor($total_time / (60 * 60)) .
// Minutes
":" . floor(($total_time % (60 * 60)) / 60) .
// Seconds
":" . $total_time % 60;
// The output is "34:50:15"
?>
那么,您预期的结果是什么?您尝试了什么?我尝试提取小时、分钟和秒,并将其存储在一个变量中,然后手动添加它们。比如秒数>60加1分钟..效果很好,先生!!我将尝试分析它是如何完成的,也许我可以用DateTime重写你的答案:)谢谢!
<?php
// Starting values
$time1 = "10:50:00";
$time2 = "24:00:15";
// First, get the times into seconds
$time1 = explode(":", $time1);
$time1 = $time1[0] * (60*60) // Hours to seconds
+ $time1[1] * (60) // Minutes to seconds
+ $time1[2]; // Seconds
$time2 = explode(":", $time2);
$time2 = $time2[0] * (60*60) // Hours to seconds
+ $time2[1] * (60) // Minutes to seconds
+ $time2[2]; // Seconds
// Add the seconds together to get the total number of seconds
$total_time = $time1 + $time2;
// Now the "tricky" part: Output it in the hh:mm:ss format.
// Use modulo to determine the hours, minutes, and seconds.
// Don't forget to round when dividing.
print
//Hours
floor($total_time / (60 * 60)) .
// Minutes
":" . floor(($total_time % (60 * 60)) / 60) .
// Seconds
":" . $total_time % 60;
// The output is "34:50:15"
?>
print
//Hours
floor($total_time / (60 * 60)) .
// Minutes
":" . date('i', $total_time) .
// Seconds
":" . date('s', $total_time);