Get Average of two java.util.Date

date, java

Solution

Well fundamentally you can just add up the "millis since the Unix epoch" of all the `Date` objects and find the average of those. Now the tricky bit is avoiding overflow. Options are:

- Divide by some known quantity (e.g. 1000) to avoid overflow; this reduces the accuracy by a known amount (in this case to the second) but will fail if you have more than 1000 items

- Divide each millis value by the number of dates you're averaging over; this will always work, but has hard-to-understand accuracy reduction

- Use `BigInteger` instead

An example of approach 1:

long totalSeconds = 0L;
for (Date date : dates) {
     totalSeconds += date.getTime() / 1000L;
}
long averageSeconds = totalSeconds / dates.size();
Date averageDate = new Date(averageSeconds * 1000L);

An example of approach 3:

BigInteger total = BigInteger.ZERO;
for (Date date : dates) {
     total = total.add(BigInteger.valueOf(date.getTime()));
}
BigInteger averageMillis = total.divide(BigInteger.valueOf(dates.size()));
Date averageDate = new Date(averageMillis.longValue());

Problem

I have an array of java.util.Date objects. I am trying to find the average. For example, if I have 2 date objects with 7:40AM and 7:50AM. I should get an average date object of 7:45AM. The approach I am thinking of is inefficient: - for loop through all dates - find difference between 0000 and time - add that time diff to a total - divide that by the total count - convert that time to a date object Is there an easier function to do this?

Original source

Related problems