Reputation: 7074
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?
Upvotes: 8
Views: 17183
Reputation: 156414
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.
Upvotes: 15
Reputation: 24780
Order the list by order of dates and perform a dichotomic search. Remember that to compare the dates you can use Date.getTime() to get the date as milliseconds, which are usually easier to compare.
Upvotes: 2
Reputation: 5452
You would order the dates by the closest.
Have a start date set to 0:
long ret = 0;
Now you need to loop though your list and keep the closest to your desired date
for(Date d : dates){
if(Math.abs(curDate.getTime() - ret) > Math.abs(curDate.getTime() - d.getTime())){
ret = d.getTime();
}
}
return new Date(ret);
The if
statement checks which date is closer by comparing the millisecond time. By using Math.abs, you eliminate direction (before or after).
Upvotes: 0
Reputation: 7838
Use Date#getTime and substract the values. The smallest result will be your closest date.
Upvotes: 3