'How to validate Hour and Minutes that came from a Swing textBox?

I have a window that contains a HH:mm time TextField in it, in 24 hours format

I need to validate if the user entered any non valid hour, like 28:00, 99:00, 24:01.

What's the best and simpler way to do that ?

some code below of what is currently doing that job wrong and giving errors in date parsed. Today I get an random hour and an user hit 99:99 in that text field.

This code is not mine, but I gotta fix it.

I am stuck with it, tried to validate as a String is useless, and I cannot find a nice way to make it a Date without having to put year, month, etc... too.

Please forget about the return -1 instead of throwing an exception this is old code and this cannot be changed.

to help understand :
Statics.hF2 = SimpleDateFormat (HH:mm)
this.cmpHora.getText() = Is the field with the value
Statics.df_ddmmyy = Another date format
Statics.m2ms = converts minutes to milliseconds

//CODE

public long getDataEmLong ()
{
   try
   {
      Calendar hour= Calendar.getInstance();
      new GregorianCalendar().
      hour.setTime( Statics.hF2.parse( this.cmpHora.getText() ) );
      return Statics.df_ddmmyy.parse( this.cmpData.getText() ).getTime() + Statics.m2ms( hour.get( Calendar.HOUR_OF_DAY ) * 60 ) + Statics.m2ms( hour.get( Calendar.MINUTE ) );
   } catch ( Exception e )
   {
      e.printStackTrace();
      return -1;
   }

}

Cheers !



Solution 1:[1]

Insert this in your class, and perform the validateTime method from inside your junk code.

public boolean validateTime(String timeString) {
    if (timeString.length() != 5) return false;
    if (!timeString.substring(2, 3).equals(":")) return false;
    int hour = validateNumber(timeString.substring(0, 2));
    int minute = validateNumber(timeString.substring(3));
    if (hour < 0 || hour >= 24) return false;
    if (minute < 0 || minute >= 60) return false;
    return true;
}

public int validateNumber(String numberString) {
    try {
        int number = Integer.valueOf(numberString);
        return number;
    } catch (NumberFormatException e) {
        return -1;
    }
}

Solution 2:[2]

Regular expressions to the rescue:

public boolean validTime24(String time) {
    return time.matches("^([01]\d|2[0-3]):[0-5]\d$")
}

This will validate the format of the string. Then you can parse out the time from there.

Solution 3:[3]

You can use JFormattedTextField with proper Date or Time Format set. The field will return you proper values.

Solution 4:[4]

Since Java 8 you can use DateTimeFormatter:

public boolean validate(String time) {
        try {
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
            timeFormatter.parse(time);
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 StanislavL
Solution 4