Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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