2013-12-11 86 views
2

我所試圖做的就是加起來小時,跨越超過24小時/分鐘/秒,例如:計算時間在PHP經過 - 跨越超過24小時

12:39:25 
08:22:10 
11:08:50 
07:33:05 

我想它是什麼返回是「39:43:30」,而不是從1970年的日期。下面是我目前使用的代碼(注意 - 它來自於一個類中,而不僅僅是一個函數)。

private function add_time($time1, $time2) 
{ 
$first_exploded = explode(":", $time1); 
$second_exploded = explode(":", $time2); 
$first_stamp = mktime($first_exploded[0],$first_exploded[1],$first_exploded[2],1,1,1970); 
$second_stamp = mktime($second_exploded[0],$second_exploded[1],$second_exploded[2],1,1,1970); 
$time_added = $first_stamp + $second_stamp; 
$sum_time = date("H:i:s",$time_added); 
return $sum_time; 
} 

任何意見,將不勝感激。

回答

1

這裏是一個不錯的小功能,將增加了任意次數在數組中傳遞: -

function addTimes(Array $times) 
{ 
    $total = 0; 
    foreach($times as $time){ 
     list($hours, $minutes, $seconds) = explode(':', $time); 
     $hour = (int)$hours + ((int)$minutes/60) + ((int)$seconds/3600); 
     $total += $hour; 
    } 
    $h = floor($total); 
    $total -= $h; 
    $m = floor($total * 60); 
    $total -= $m/60; 
    $s = floor($total * 3600); 
    return "$h:$m:$s"; 
} 

使用方法如下: -

$times = array('12:39:25', '08:22:10', '11:08:50', '07:33:05',); 
var_dump(addTimes($times)); 

輸出: -

string '39:43:30' (length=8) 
+0

這對我正在嘗試做的事更好,因爲他們通常是7次生病添加,所有這些都已經在數組中 - 保存我運行另一個foreach循環:-)。謝謝 – Smithey93

3

日期函數總是有效/有日/月/年。 你想要的是一個簡單的數學函數,沒有測試它,但應該說清楚。

private function add_time($base, $toadd) { 
    $base = explode(':', $base); 
    $toadd = explode(':', $toadd); 

    $res = array(); 
    $res[0] = $base[0] + $toadd[0]; 
    $res[1] = $base[1] + $toadd[1]; 
    $res[2] = $base[2] + $toadd[2]; 
    // Seconds 
    while($res[2] >= 60) { 
     $res[1] += 1; 
     $res[2] -= 60; 
    } 
    // Minutes 
    while($res[1] >= 60) { 
     $res[0] += 1; 
     $res[1] -= 60; 
    } 
    return implode(':', $res); 
} 
+0

第一次工作 - 感謝您的幫助! – Smithey93