Java Data Type How to - Find date nearest to target in a list of dates








Question

We would like to know how to find date nearest to target in a list of dates.

Answer

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TreeSet;
/*  w ww  .  j a v  a2 s. c o m*/
public class Main {
  public static void main(String[] args) throws ParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
        "dd.MM.yyyy HH:mm:ss");

    List<Date> otherDates = Arrays.asList(new Date[] {
        simpleDateFormat.parse("01.01.2015 01:00:00"),
        simpleDateFormat.parse("01.01.2015 01:00:02") });
    
    
    System.out.println(get(otherDates, simpleDateFormat.parse("01.01.2015 01:00:01")));
    System.out.println(get(otherDates, simpleDateFormat.parse("01.01.2015 01:00:03")));
    System.out.println(get(otherDates, simpleDateFormat.parse("01.01.2015 01:00:00")));
  }

  public static Date get(List<Date> otherDates, Date dateToApproach) {
    final TreeSet<Date> set = new TreeSet<Date>(otherDates);
    set.add(dateToApproach);
    final ArrayList<Date> list = new ArrayList<Date>(set);
    final int indexOf = list.indexOf(dateToApproach);
    if (indexOf == 0)
      return null;
    return list.get(indexOf - 1);
  }
}

The code above generates the following result.