Average between multiple dates in an array

Asked

Viewed 769 times

2

I am needing to calculate an average not only between an initial date and a final date, but on all dates present in a matrix to obtain an average result in days, hours, minutes and seconds of how much X in X time such an event is recorded.

I have already developed a basis for this calculation but it does not seem to be correct, because let’s look at the example:

$dates = ['2015-05-10 12:00:00', '2015-05-11 12:00:00', '2015-05-12 12:00:00'];
$dates = array_map('strtotime', $dates);

for($count = count($dates), $result = 0, $i = 1; $i < $count; $i++)
{
    $result += $dates[$i-1] - $dates[$i];
}

$seconds = floor($result / $count);

$DTF = new DateTime("@0");
$DTT = new DateTime("@$seconds");
echo $DTF->diff($DTT)->format('%a dias, %h horas, %i minutos e %s segundos');

In the array, the difference between these 3 dates is exactly 24 hours, but the result since the calculation is: 0 dias, 16 horas, 0 minutos e 0 segundos, what could be wrong?

  • The expected result is?

1 answer

2


Because at the end of the loop $result stored the two differences (24 + 24 = 48 hours) but divided by the amount of indexes (3).

The right thing would be $seconds = floor($result / $count - 1) because although you have 3 dates, you have only 2 intervals between them.

  • True, I came to this very result just now, that’s exactly it!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.