-4

I have list of dates:

23/08/2014 8:23:23
24/08/2014 5:23:23
24/08/2014 6:23:23
24/08/2014 7:23:23
24/08/2014 7:25:23
24/08/2014 8:23:23

I want to compare all dates to current date time and find the closest date time. Is there any simple way to compare them instead of looping and comparing?

I have tried below example

Date1.after(date2)

date1.compareTo(date2)>0

But I not able to accomplish the result.

I have to compare entire date and time not only date or time

by using below format i have to compare

Date currentTimeDate = new Date(System.currentTimeMillis());

isha
  • 349
  • 2
  • 12
  • 2
    Have you done any code for this? – Pratik Butani Aug 24 '15 at 12:13
  • http://stackoverflow.com/a/3884728/1318946 – Pratik Butani Aug 24 '15 at 12:19
  • http://stackoverflow.com/questions/186311/best-way-to-find-date-nearest-to-target-in-a-list-of-dates?rq=1 – user2864740 Aug 24 '15 at 12:21
  • i can't reply anymore so i write here: Calendar cal = Calendar.getInstance(); long actualDateMs = cal.getTimeMillis(); long distance = Math.abs(actualDateMs - ListOfDate[0].GetTime()); //GetTime() or whichever methods give you milliseconds from date int index = 0; for(int i = 1; i < ListOfDate.length; i++){ long distancePartial = Math.abs(actualDateMs - ListOfDate[i].GetTime()); if(distancePart < distance){ distance = distancePart; index = i; } } at the end the `index` value is the index of the closest date in the list – Pier Giorgio Misley Aug 24 '15 at 12:40

2 Answers2

2
  • Make the list of your Date Objects in a sorted way.
  • Then create a Date object for current Date time.

  • Now use the logic of Binary search to find the closest Date Time in your list.

  • Use Joda Time for comparison.

Consider the above points as hint.

Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
0

Try this snippet, It will may be helpful to you.

public static Date closerDate(Date originalDate, Collection<Date> unsortedDates) {
    List<Date> dateList = new LinkedList<Date>(unsortedDates);
    Collections.sort(dateList);
    Iterator<Date> iterator = dateList.iterator();
    Date previousDate = null;
    while (iterator.hasNext()) {
        Date nextDate = iterator.next();
        if (nextDate.before(originalDate)) {
            previousDate = nextDate;
            continue;
        } else if (nextDate.after(originalDate)) {
            if (previousDate == null || isCloserToNextDate(originalDate, previousDate, nextDate)) {
                return nextDate;
            }
        } else {
            return nextDate;
        }
    }
    return previousDate;
}

private static boolean isCloserToNextDate(Date originalDate, Date previousDate, Date nextDate) {
    if(previousDate.after(nextDate))
        throw new IllegalArgumentException("previousDate > nextDate");
    return ((nextDate.getTime() - previousDate.getTime()) / 2 + previousDate.getTime() <= originalDate.getTime());
}
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437