Average time in hours,minutes and seconds in php

后端 未结 3 1395
别跟我提以往
别跟我提以往 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"
    
    0 讨论(0)
  • 2020-12-18 12:19

    Close to Antony's solution, but with array of hours given:

    $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;
    
    0 讨论(0)
  • 2020-12-18 12:19
    1. The best way would be to change the total hour value in seconds.
    2. Divide it by total count value. What you will get is average in seconds.
    3. Convert average back in H:m:s format.
    0 讨论(0)
提交回复
热议问题