Get Average of two java.util.Date -
i have array of java.util.date objects. trying find average.
for example, if have 2 date objects 7:40am , 7:50am. should average date object of 7:45am.
the approach thinking of inefficient:
- for loop through dates
- find difference between 0000 , time
- add time diff total
- divide total count
- convert time date object
is there easier function this?
well fundamentally can add "millis since unix epoch" of date
objects , find average of those. tricky bit avoiding overflow. options are:
- divide known quantity (e.g. 1000) avoid overflow; reduces accuracy known amount (in case second) fail if have more 1000 items
- divide each millis value number of dates you're averaging over; work, has hard-to-understand accuracy reduction
- use
biginteger
instead
an example of approach 1:
long totalseconds = 0l; (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; (date date : dates) { total = total.add(biginteger.valueof(date.gettime())); } biginteger averagemillis = total.divide(biginteger.valueof(dates.size())); date averagedate = new date(averagemillis.longvalue());
Comments
Post a Comment