首页javalegacy_dateJava Data Type - 如何在日期列表中找到距离目标最近的日期

Java Data Type - 如何在日期列表中找到距离目标最近的日期

我们想知道如何在日期列表中找到距离目标最近的日期。
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;

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);
  }
}