Search code examples
javajava.util.datedate

Compare calendar time by minutes


I'd like to calculate the difference between "MON 17:00" and "Tue 5:00" in "minutes" How can I achieve this using Java. I don't quite understand how to use calendar and simpleDateFormat doesn't support the Mon,Tue,Wed,e.t.c feature. Any help?

The problem only involves week therefore "SUN 00:00" as the earliest and "SAT 23:59" as the latest.

P.S. given many strings in that format, I also would like to sort them from what happens first, to what happens last. Because I think sorting them first would make the task (determining the difference) easier.


Solution

  • May be something like this

    import java.text.SimpleDateFormat;
    import java.util.Locale;
    import java.util.concurrent.TimeUnit;
    
    public class DateCompare {
    
        public static void main(String[] args) {
            try {
                final String start = "Mon 17:00";
                final String end = "Tue 5:00";
                SimpleDateFormat formatter = new SimpleDateFormat("EEE HH:mm", Locale.US);
                long diffMinutes = TimeUnit.MILLISECONDS.toMinutes(formatter.parse(end).getTime() - formatter.parse(start).getTime()); 
                System.out.println(diffMinutes + " minutes");
            } catch(Exception ex) {
                ex.printStackTrace();
            }
    
        }
    
    }