Time average in hours

丶灬走出姿态 提交于 2019-12-12 02:29:41

问题


I wanted to get an average hours but I'm having problems because if I use DateTime.add() object for adding time when it exceeds 24 hours it converts time to "day". Basically I just want to get the average of these times in "hours". Please help.

$time = array();
$time[] = '00:00:58';
$time[] = '00:45:08';
$time[] = '00:00:49';
$time[] = '00:11:26';
$time[] = '02:34:39';
$time[] = '02:18:24';
$time[] = '02:24:11';
$time[] = '01:23:19';
$time[] = '00:27:30';
$time[] = '02:14:50';
$time[] = '00:48:47';
$time[] = '02:19:52';
$time[] = '02:04:29';
$time[] = '01:08:46';
$time[] = '00:06:57';
$time[] = '00:35:31';
$time[] = '02:16:59';
$time[] = '02:23:33';
$time[] = '02:36:30';
$time[] = '02:11:47';
$time[] = '02:40:44';
$time[] = '02:03:42';
$time[] = '01:45:50';

回答1:


Try this,

$total_time=0;

foreach($time as $t){
     $total_time+=strtotime($t)-1373241600;
}

So $total_time will be an integer number and you can divide it with 3600 and with count($time) to get average hour :)

$average_time = ($total_time/count($time))/3600;



回答2:


Try this (note closures are available in 5.3+):

$timestamps = array_map(function($a){return strtotime($a);}, $time);
$avg = (array_sum($timestamps)/count($timestamps))/3600;



回答3:


If you do not want to rely on timezone settings, subtract timestamp for current day or annoyed with sluggishness of strtotime, use simple math instead:

$timestamps = array_map(function($item){
    list($h, $m, $s) = explode(':', $item);
    return intval($h) * 3600 + intval($m) * 60 + intval($s);
}, $time);
$avg = ceil(array_sum($timestamps)/count($timestamps));
echo gmdate('H:i:s', $avg);


来源:https://stackoverflow.com/questions/17534074/time-average-in-hours

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