Basically, you can simply add the βmillions from the Unix eraβ of all Date objects and find the average of them. Now a complex bit avoids overflow. Possible options:
- Divide by a known amount (e.g. 1000) to avoid overflow; this reduces accuracy by a known amount (in this case, by a second), but will fail if you have more than 1000 elements.
- Divide each millis value by the number of dates you average; it will always work, but has a difficult to understand decrease in accuracy
- Use
BigInteger instead
Approach Example 1:
long totalSeconds = 0L; for (Date date : dates) { totalSeconds += date.getTime() / 1000L; } long averageSeconds = totalSeconds / dates.size(); Date averageDate = new Date(averageSeconds * 1000L);
Approach Example 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());
source share