4

I have ArrayList<D> details;

public class D {
    String time;
}

I want to find nearest to current date & time and it should give me at which position it is nearest.

 private Date getDateNearest(List<Date> dates, Date targetDate) {
    Date returnDate = targetDate;
    for (Date date : dates) {
        // if the current iteration'sdate is "before" the target date
        if (date.compareTo(targetDate) <= 0) {
            // if the current iteration's date is "after" the current return date
            if (date.compareTo(returnDate) > 0) {
                returnDate = date;
            }
        }
    }
    return returnDate;
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
bob
  • 155
  • 3
  • 13

1 Answers1

4

You could try using the following function:

Please make sure that you have to pass List of Date objects (List<Date>) instead of your ArrayList<D> details. You can convert String to Date using SimpleDateFormat.

  public void getNearestDate(List<Date> dates, Date targetDate) {
    Date nearestDate = null;
    int index = 0;
    long prevDiff = -1;
    long targetTS = targetDate.getTime();
    for (int i = 0; i < dates.size(); i++) {
        Date date = dates.get(i);
        long currDiff = Math.abs(date.getTime() - targetTS);
        if (prevDiff == -1 || currDiff < prevDiff) {
            prevDiff = currDiff;
            nearestDate = date;
            index = i;
        }
    }
    System.out.println("Nearest Date: " + nearestDate);
    System.out.println("Index: " + index);
}
Sanif SS
  • 602
  • 5
  • 18