【问题标题】:Average time in hours,minutes and seconds in phpphp中以小时、分钟和秒为单位的平均时间
【发布时间】:2013-02-05 12:49:11
【问题描述】:

我有一些总小时数,需要计算平均值。例如,我的总小时值为 2452:43:44 (H:m:s),总计数为 15。我想以相同的格式获取平均时间,即小时:分钟:秒。我们如何在 PHP 中做到这一点?

【问题讨论】:

  • 你的意思可能是h:i:s

标签: php average


【解决方案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"

【讨论】:

  • 如何计算 ("163:30:54" * 15) 那么它必须等于 "2452:43:44" 以供检查?
  • @Akam 我有一个能够计算时间/角度的计算器:2452:43:44 / 15 = 163:30:54.93。尽管存在一些小的舍入误差,但计算是正确的。
  • 您能解释一下$count 变量的用途吗?
  • @rar 如果你看一下这个问题,它是关于从总时间计算平均值。这就像一个数字除以另一个数字,只是初始值和结果以h:i:s格式表示。 $count 这里是除数,在这种情况下是第二个数字。
  • 谢谢,我忽略了。
【解决方案2】:

接近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;

【讨论】:

    【解决方案3】:
    $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;
    }
    

    【讨论】:

      【解决方案4】:
      1. 最好的方法是以秒为单位更改总小时值。
      2. 除以总计数值。您将获得的结果是平均秒数。
      3. 将平均值转换回 H:m:s 格式。

      【讨论】:

      • 你的意思可能是h:i:s
      • @DainisAbols:感谢您的观察,但 Alwin 在他的问题中指定了 H:m:s,所以我这样提到。感谢您的努力。
      • @BhavikShah 谢谢伙计...我选择了第一个。无论如何感谢您的回答。也谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多