Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> times = Arrays.asList(new String[] { "03:00 AM", "12:30 PM", "16:15" });
        Collections.sort(times, new TimeStringComparator());
        System.out.println(times);
    }
}

class TimeStringComparator implements Comparator<String> {
    private DateFormat primaryFormat = new SimpleDateFormat("h:mm a");
    private DateFormat secondaryFormat = new SimpleDateFormat("H:mm");

    @Override
    public int compare(String time1, String time2) {
        return timeInMillis(time1) - timeInMillis(time2);
    }

    public int timeInMillis(String time) {
        return timeInMillis(time, primaryFormat);
    }

    private int timeInMillis(String time, DateFormat format) {
        try {
            Date date = format.parse(time);
            return (int) date.getTime();
        } catch (ParseException e) {
            if (format != secondaryFormat) {
                return timeInMillis(time, secondaryFormat);
            } else {
                System.out.println(e);
                return -1;
            }
        }
    }

}