Average time in hours,minutes and seconds in php

时间秒杀一切 提交于 2019-11-28 01:40:58

问题


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 average time in the same format, that is hours:minutes:seconds. How can we do it in PHP ?


回答1:


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:


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;



回答3:


  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.


来源:https://stackoverflow.com/questions/14707964/average-time-in-hours-minutes-and-seconds-in-php

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