1

How can I get the nearest future date from a list of dates with compared to the date I pass? For example, I have list of 3 class objects which has dates property 10 January, 20 January and 30 January respectively. And I have one date object which is 15 January. Now when I pass date 15 Jan, it should return object of 20 January. and if I pass date 25 January , it should return object of 30 January. Is that even possible?

Aakash Patel
  • 549
  • 5
  • 19
  • yes it is possible. try the methods `date.before(date2)` and `date.after(date2)`. with these its possible – XtremeBaumer Dec 06 '16 at 07:23
  • Easiest way is to order the list then loop through comparing the adjacent list elements. If the list is large, look into writing a comparison in conjunction with a common search algorithm. – the happy mamba Dec 06 '16 at 07:24
  • Also duplicate of http://stackoverflow.com/q/2592501. Please search Stack Overflow before posting. – Basil Bourque Dec 06 '16 at 08:28

2 Answers2

3

You search through the list of dates, ignore any dates that are before your reference date, then remember the earliest of those dates.

Remembering the earliest date is like a regular loop for finding the minimum value.

Example:

private static Optional<LocalDate> findNext(LocalDate refDate, LocalDate[] dates) {
    LocalDate next = null;
    for (LocalDate date : dates)
        if (! date.isBefore(refDate) && (next == null || date.isBefore(next)))
            next = date;
    return Optional.ofNullable(next);
}

Test

LocalDate[] dates = { LocalDate.of(2016, 1, 10),
                      LocalDate.of(2016, 1, 20),
                      LocalDate.of(2016, 1, 30) };
System.out.println(findNext(LocalDate.of(2016, 1,  5), dates));
System.out.println(findNext(LocalDate.of(2016, 1, 15), dates));
System.out.println(findNext(LocalDate.of(2016, 1, 25), dates));
System.out.println(findNext(LocalDate.of(2016, 2,  1), dates));

Output

Optional[2016-01-10]
Optional[2016-01-20]
Optional[2016-01-30]
Optional.empty
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

Sort the collection by date using Collections.sort and iterate over the list comparing the current date passed as parameter and using Calendar class identify the smaller difference by API to identify difference between two dates

Community
  • 1
  • 1
snofty
  • 70
  • 7