How would I go about finding the closest date to a specified date? (Java)
I was hopi开发者_运维百科ng 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?
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.
Use Date#getTime and substract the values. The smallest result will be your closest date.
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.
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).
精彩评论