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?
Use Date#getTime and substract the values. The smallest result will be your closest date.
Finding the future closest date to today in Excel 1. Select the blank cell B2, copy and paste formula =MIN(IF(A2:A18>TODAY(),A2:A18)) into the Formula Bar, and then press Ctrl + Shift + Enter keys simultaneously. See screenshot: Then you will get the future closest date to today in cell B2.
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
The LocalDateTime. now() method returns the instance of LocalDateTime class. If we print the instance of LocalDateTime class, it prints the current date and time. To format the current date, you can use DateTimeFormatter class which is included in JDK 1.8.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With