Average time in hours,minutes and seconds in php

心不动则不痛 提交于 2019-11-29 08:24:54
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"
Peon

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;
Bhavik Shah
  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.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!