Reputation: 4682
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 ?
Upvotes: 3
Views: 5288
Reputation: 305
$totalhourandmunite+=str_replace(":",'',$date);
strtoheur(round($totalhourandmunite/$nbdate,0));
function strtoheur($temp)
{
if(strlen($temp)==1) return $temp;
if(strlen($temp)==2)
$temp=$temp."00";
if(strlen($temp)==3)
$temp="0".$temp;
$temp=str_split($temp);
$heure=$temp["0"].$temp["1"];
$min=$temp["2"].$temp["3"];
if($min/60>1)
{
$min=$min%60;
$heure++;
}
if($min<10 && strlen($min)==1)
$min="0".$min;
if($heure>23)
{
$heure=$heure%24;
}
$temp=$heure.":".$min;
return $temp;
}
Upvotes: 1
Reputation: 15106
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"
Upvotes: 4
Reputation: 2291
Upvotes: 0
Reputation: 8030
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;
Upvotes: 2