Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I go about finding the closest date to a specified date? (Java)

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?

like image 253
Dylan Wheeler Avatar asked Aug 20 '11 00:08

Dylan Wheeler


People also ask

How to find closest date in Java?

Use Date#getTime and substract the values. The smallest result will be your closest date.

How do I find the closest date from today?

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.

How do you check if a date is before another date in Java?

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.

Which is the most up to date way to instantiate the current date in Java?

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.


3 Answers

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.

like image 185
maerics Avatar answered Oct 07 '22 01:10

maerics


Use Date#getTime and substract the values. The smallest result will be your closest date.

like image 22
dertkw Avatar answered Oct 07 '22 01:10

dertkw


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.

like image 2
SJuan76 Avatar answered Oct 07 '22 01:10

SJuan76