【发布时间】:2013-02-05 12:49:11
【问题描述】:
我有一些总小时数,需要计算平均值。例如,我的总小时值为 2452:43:44 (H:m:s),总计数为 15。我想以相同的格式获取平均时间,即小时:分钟:秒。我们如何在 PHP 中做到这一点?
【问题讨论】:
-
你的意思可能是
h:i:s。
我有一些总小时数,需要计算平均值。例如,我的总小时值为 2452:43:44 (H:m:s),总计数为 15。我想以相同的格式获取平均时间,即小时:分钟:秒。我们如何在 PHP 中做到这一点?
【问题讨论】:
h:i:s。
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"
【讨论】:
2452:43:44 / 15 = 163:30:54.93。尽管存在一些小的舍入误差,但计算是正确的。
$count 变量的用途吗?
h:i:s格式表示。 $count 这里是除数,在这种情况下是第二个数字。
接近Antony's 解决方案,但给定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;
【讨论】:
$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;
}
【讨论】:
【讨论】:
h:i:s。