I have an array of objects which the app gets from a WebService, each object has a createdTime and objects are created randomly from 6 in the morning to midnight.
I want to know what is the average time between each object creation. What is the best and most efficient way to implement it?
The dates are in this format: "CreatedTime": "2019-02-18T22:06:30.523"
The average date interval is the time elapsed between the first and last date and divide by
n-1, the number of intervals. That’s going to be most efficient.This works because the average is equal to the sum of the intervals divided by the number of intervals. But the sum of all the intervals is equal to the difference between the first and last date.
Assuming your date strings are already in order, just grab the first and last, calculate the difference and divide.
That’s in seconds. If you’d like a nice string format and don’t care about milliseconds, the
DateComponentsFormatteris convenient for localized strings:That produces:
Or you can, less efficiently, build the
datesarray:Then you could build an array of intervals between those dates:
And then average them:
And format to taste: