Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare Time in java/android (given input in strings)?

Tags:

java

android

I have two strings which are used to store time in the format hh:mm.I want to the compare these two to know which time is greater.Which is the easiest way to go about this?

like image 923
rogerstone Avatar asked Feb 26 '11 09:02

rogerstone


2 Answers

Use the SimpleDateFormat and Date classes. The latter implements Comparable, so you should be able to use the .compareTo() method to do the actual comparison. Example:

            String pattern = "HH:mm";
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            try {
                Date date1 = sdf.parse("19:28");
                Date date2 = sdf.parse("21:13");

                // Outputs -1 as date1 is before date2
                System.out.println(date1.compareTo(date2));

                // Outputs 1 as date1 is after date1
                System.out.println(date2.compareTo(date1));

                date2 = sdf.parse("19:28");         
                // Outputs 0 as the dates are now equal
                System.out.println(date1.compareTo(date2));

            } catch (ParseException e){
                // Exception handling goes here
            }

See the SimpleDateFormat documentation for patterns.

like image 148
hanspeide Avatar answered Sep 21 '22 13:09

hanspeide


Well, if they're actually hh:mm (including leading zeroes, and in 24-hour format) then you can just compare them lexicographically (i.e. using String.compareTo(String)). That's the benefit of a sortable format :)

Of course, that won't check that both values are valid times. If you need to do that, you should probably parse both times: check the length, check the colon, parse two substrings, and probably multiply the number of hours by 60 and add it to the number of minutes to get a total number of minutes. Then you can compare those two totals.

EDIT: As mentioned in the comments, if you do need to parse the values for whatever reason, personally I would recommend using Joda Time (possibly a cut down version, given the mobile nature) rather than SimpleDateTimeFormat and Date. Joda Time is a much nicer date and time API than the built-in one.

like image 35
Jon Skeet Avatar answered Sep 21 '22 13:09

Jon Skeet