如何在php中为字符串格式时间添加超过24小时的小时数,分钟数和秒数? ex。计算总小时
$time1 = '10:50:00';
$time1 = '24:00:15';
它的结果将是: '34:00:15'
如何在php中为字符串格式时间添加超过24小时的小时数,分钟数和秒数? ex。计算总小时
$time1 = '10:50:00';
$time1 = '24:00:15';
它的结果将是: '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"
?>
因为你是新来的PHP,我已经做到了这一点使用功能,而不是日期时间,因为OOP在PHP可能使你更难理解这里发生了什么。但是,如果您在PHP中学习OOP,使用DateTime重写我的答案可能是一种有趣的练习。
编辑:我已经意识到,你可以用date()
得到分和秒的数目,而不是一个模。如果你愿意的话,你可以用这样的东西替换最后的打印语句:
print
//Hours
floor($total_time/(60 * 60)) .
// Minutes
":" . date('i', $total_time) .
// Seconds
":" . date('s', $total_time);
作品伟大的先生!我会尝试分析它是如何完成的,可能我可以使用DateTime重写你的答案:)谢谢! –
那么,你的预期结果是什么,你试过了什么? – Ravi
https://stackoverflow.com/questions/30073976/show-php-time-as-hours-greater-than-24-hrs-like-70-hrs – clearshot66
我试图通过提取小时,分钟,秒和存储它在一个变量中,然后手动添加它们。如果第二个> 60加1分钟.. –