rogerstone
rogerstone

Reputation: 7671

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

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?

Upvotes: 8

Views: 22782

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502086

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.

Upvotes: 12

Wroclai
Wroclai

Reputation: 26925

I have written functions for this before in my Android program and I will gladly share the source below.

Functions (will explain later using "how to use" code):

public static void String setFormattedTimeString(final String formatExpr,
                                   final long timeStampInSeconds) {     
    final Date dateFromTimeStamp = new Date(timeStampInSeconds);        
    final SimpleDateFormat simpleformat = new SimpleDateFormat(formatExpr);
    final String formattedDateInString = simpleformat.format(dateFromTimeStamp);        
    return formattedDateInString;
}

public static void Calendar setCalendar(final int year, final int month,
                                    final int day) {            
    final Calendar calendar = Calendar.getInstance();           
    calendar.set(Calendar.DAY_OF_MONTH, day);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.YEAR, year);
    return calendar;            
}

public static void double timeDifferenceInDays(final Calendar firstDate,
                                     final Calendar secondDate) {
    final long firstDateMilli = firstDate.getTimeInMillis();
    final long secondDateMilli = secondDate.getTimeInMillis();
    final long diff = firstDateMilli - secondDateMilli;   

    // 24 * 60 * 60 * 1000 because I want the difference in days. Change
    // as your wish. 
    final double diffDays = (double) diff / (double) (24 * 60 * 60 * 1000);

    return diffDays;
}

And this is how I use them to calculate difference (days in this example). In this example I'm assuming you have a timestamp to use, otherwise you can change easily:

// Here you maybe have a timestamp in seconds or something..    

// This is ONE Calendar.
final String yearString = MyToolClass.setFormattedTimeString("y", timestamp);
final int year = Integer.parseInt(yearString);                                                   
final String monthString = MyToolClass.setFormattedTimeString("M", timestamp);
final int month = Integer.parseInt(monthString);                                      
final String day_in_monthString = MyToolClass.setFormattedTimeString("d",
                                        timestamp);
final int day_of_month = Integer.parseInt(day_in_monthString);

final Calendar calendarOne = MyToolClass.setCalendar(year, month,
                                        day_of_month);   

// Same stuff for Calendar two.

// Calculate difference in days.
final double differenceInDays = MyToolClass.timeDifferenceInDays(calendarOne,
                                        calendarTwo); 

Upvotes: 3

user340145
user340145

Reputation:

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.

Upvotes: 23

Related Questions