Average time in hours,minutes and seconds in php

后端 未结 3 1408
别跟我提以往
别跟我提以往 2020-12-18 11:50

I have some total sums of hours and need to calculate the average. For example, my total hour value is 2452:43:44 (H:m:s) and the total count is 15. I would like to get the

3条回答
  •  生来不讨喜
    2020-12-18 12:05

    function average_time($total, $count, $rounding = 0) {
        $total = explode(":", strval($total));
        if (count($total) !== 3) return false;
        $sum = $total[0]*60*60 + $total[1]*60 + $total[2];
        $average = $sum/(float)$count;
        $hours = floor($average/3600);
        $minutes = floor(fmod($average,3600)/60);
        $seconds = number_format(fmod(fmod($average,3600),60),(int)$rounding);
        return $hours.":".$minutes.":".$seconds;
    }
    echo average_time("2452:43:44", 15); // prints "163:30:55"
    echo average_time("2452:43:44", 15, 2); // prints "163:30:54.93"
    

提交回复
热议问题