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:

  1. for loop through dates
  2. find difference between 0000 , time
  3. add time diff total
  4. divide total count
  5. 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:

  1. divide known quantity (e.g. 1000) avoid overflow; reduces accuracy known amount (in case second) fail if have more 1000 items
  2. divide each millis value number of dates you're averaging over; work, has hard-to-understand accuracy reduction
  3. 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

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -