Search code examples
javatimecomparison

Time comparison


I have a time in hh:mm and it has to be entered by the user in that format.

However, I want to compare the time (eg. 11:22) is it between 10am to 6pm? But how do I compare it?


Solution

  • Java doesn't (yet) have a good built-in Time class (it has one for JDBC queries, but that's not what you want).

    One option would be use the JodaTime APIs and its LocalTime class.

    Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date comparison functions to see if it is before or after some other time:

    SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
    Date ten = parser.parse("10:00");
    Date eighteen = parser.parse("18:00");
    
    try {
        Date userDate = parser.parse(someOtherDate);
        if (userDate.after(ten) && userDate.before(eighteen)) {
            ...
        }
    } catch (ParseException e) {
        // Invalid date was entered
    }
    

    Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:

    Pattern p = Pattern.compile("(\d{2}):(\d{2})");
    Matcher m = p.matcher(userString);
    if (m.matches() ) {
        String hourString = m.group(1);
        String minuteString = m.group(2);
        int hour = Integer.parseInt(hourString);
        int minute = Integer.parseInt(minuteString);
    
        if (hour >= 10 && hour <= 18) {
            ...
        }
    }
    

    It really all depends on what you are trying to accomplish.