Johan Magos
Johan Magos

Reputation: 19

How to get time average

I have a time calculations problem in getting average.

I have this summed up call time 06:03:05 and I want to get an average with 175 calls.

    date_default_timezone_set('America/Chicago');
    $ts =  strtotime("06:03:05");
    echo date("H:i:s", $ts/175);

I get: 12:26:25

I'm not even sure why I come up with this very huge time average. Am I doing this right? Please help.

Upvotes: 1

Views: 399

Answers (2)

bitWorking
bitWorking

Reputation: 12665

One easy way which only works up to 24 hours. Else take Atlis approach and search also for a way to convert seconds to date.

$time = '06:03:05';
$seconds = strtotime("1970-01-01 $time UTC");
$average = $seconds/175;
echo gmdate('H:i:s', $average);

Upvotes: 0

Atli
Atli

Reputation: 7930

The problem there is that your strtotime call, not having a date component, is defaulting to the current date. So the $ts is a much much larger number than just the sum of the time parts; it includes the date parts as well.

I would avoid using the time functions like that. It's simple enough to calculate the number of seconds based on the hours, minutes and seconds. Once you have that, you can use date() to echo the formatted time like you do there.

Try something more like this:

function getTimeAverage($hours, $minutes, $seconds, $division) {
    $seconds += ($hours * 3600) + ($minutes * 60);
    return $seconds / $division;
}

$average = getTimeAverage(6, 3, 5, 175);

echo gmdate("H:i:s", $average);

Upvotes: 1

Related Questions