如何在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分鐘.. –