Search code examples
phptimestampaveragedate-difference

Calculate average time difference between multiple unix timestamps


i feel a little bit stupid, but let's imagine, that i have a set of unix timestamps:

1375110404
1374660925
1374482694
1374242337
1373793867
1373632889
1373187141
1373021668
1372754021
1372599890

What i'm trying to achieve is simple: I just want to calculate the average time difference between these 10 timestamps. I just can't find the proper way for the calculation.

What i just tried was

1375110404 - 1374660925 = 449479
1374482694 - 1374242337 = 240357
1373793867 - 1373632889 = 160978
1373187141 - 1373021668 = 165473
1372754021 - 1372599890 = 154131

449479 + 240357 + 160978 + 165473 + 154131 = 1170418

1170418 / 5 = 234083,6

but that looks illogical to me. Any advice is greatly appreciated.

EDIT:

All these stamps come from a php array.

EDIT:

Thanks to Orangepill for pointing me to the right direction. Here's the final solution:

for($cnt = count($array), $res = 0, $i = 1; $i < $cnt; $i++) {
    $res += $array[$i-1] - $array[$i];
}

echo $res/$cnt;

This calculates

1375110404 - 1374660925 = 449479
1374660925 - 1374482694 = 178231
1374482694 - 1374242337 = 240357
1374242337 - 1373793867 = 448470
1373793867 - 1373632889 = 160978
1373632889 - 1373187141 = 445748
1373187141 - 1373021668 = 165473
1373021668 - 1372754021 = 267647
1372754021 - 1372599890 = 154131

449479 + 178231 + 240357 + 448470 + 160978 + 445748 + 165473 + 267647 + 154131 = 2510514

2510514 / 10 = 251051.4

which looks correct to me.


Solution

  • The most straight forward way it to do it like you described.

     $res =0;
     for($x = 1, $num = count($array); $x < $num; $x++){
         $res =+ $array[$x] - $array[$x-1];
     }
     echo $res/($num-1);