簡體   English   中英

計算經過php的時間-跨越24小時

[英]Calculate time elapsed in php - spans over 24 hours

我正在嘗試做的是總計超過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;
}

任何建議將不勝感激。

日期功能始終圍繞/與日/月/年一起使用。 您想要的是一個簡單的數學函數,並未對其進行測試,但應明確說明。

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);
}

這是一個不錯的小函數,它將增加在數組中傳遞的任何次數:-

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM