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?
You can solve in linear time by computing the difference in time (e.g.
Date#getTime()) and returning the minimum:[Edit]
Minor performance improvements.