How would I go about finding the closest date to a specified date? (Java)

Confiqure picture Confiqure · Aug 20, 2011 · Viewed 12.2k times · Source

I was hoping to know how I would type up a method to give me the closest date to a specified date. What I mean is something along the following:

public Date getNearestDate(List<Date> dates, Date currentDate) {
    return closestDate  // The date that is the closest to the currentDate;
}

I have found similar questions, but only one had a good answer and the code kept giving me NullPointerExceptions ... Can anyone help me?

Answer

maerics picture maerics · Aug 20, 2011

You can solve in linear time by computing the difference in time (e.g. Date#getTime()) and returning the minimum:

public static Date getNearestDate(List<Date> dates, Date currentDate) {
  long minDiff = -1, currentTime = currentDate.getTime();
  Date minDate = null;
  for (Date date : dates) {
    long diff = Math.abs(currentTime - date.getTime());
    if ((minDiff == -1) || (diff < minDiff)) {
      minDiff = diff;
      minDate = date;
    }
  }
  return minDate;
}

[Edit]

Minor performance improvements.