Average time in hours, minutes and seconds in php

I have several 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 is 15. I would like to get the average time in the same format as hours: minutes: seconds. How can we do this in PHP?

+3


source to share


3 answers


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"

      



+2


source


Next to Antony's solution , but with an array hours

:



$time = array (
            '2452:43:44',
            '452:43:44',
            '242:43:44',
            '252:43:44',
            '2:43:44'
        );

$seconds = 0;
foreach($time as $hours) {
    $exp = explode(':', strval($hours));
    $seconds += $exp[0]*60*60 + $exp[1]*60 + $exp[2];
}

$average = $seconds/sizeof( $time );
echo floor($average/3600).':'.floor(($average%3600)/60).':'.($average%3600)%60;

      

+2


source


  • The best way is to change the total hour in seconds.
  • Divide it by the total count. What you get is the average in seconds.
  • Converting the mean in the H: m: s format.
0


source







All Articles