How do I find the closest date to a specified date? (Java)

I was hoping to find out how I am typing a method to give me the closest date to the specified date. I mean the following:

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

I found similar questions, but only one had a good answer, and the code continued to give me NullPointerExceptions ... Can anyone help me?

+5
source share
4 answers

You can solve the linear time by calculating the time difference (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;
}

[change]

Minor performance improvements.

+12
source

Use Date # getTime and subtract the values. The smallest result will be your nearest date.

+3

. , Date.getTime(), , .

+2

.

0:

long ret = 0;

for(Date d : dates){
    if(Math.abs(curDate.getTime() - ret) > Math.abs(curDate.getTime() - d.getTime())){
        ret = d.getTime();
    }
}
return new Date(ret);

if , , . Math.abs, ( ).

0

All Articles