Regular expression time in 24 hours format pattern
([01]?[0-9]|2[0-3]):[0-5][0-9] |
([01]?[0-9]|2[0-3]):[0-5][0-9]
This regular expression refers to a pattern which start from 0-23 or 00-23 then a semi colon (:) and follow by 00-59.
Example
package com.w3spoint;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
private static final String PATTERN =
"([01]?[0-9]|2[0-3]):[0-5][0-9]";
public static void main(String args[]){
List<String> values = new ArrayList<String>();
values.add("05:00");
values.add("17:01");
values.add("24:00");
values.add("13:1");
Pattern pattern = Pattern.compile(PATTERN);
for (String value : values){
Matcher matcher = pattern.matcher(value);
if(matcher.matches()){
System.out.println("Time "+ value +" is valid 24Hours Format");
}else{
System.out.println("Time "+ value +" is invalid 24Hours Format");
}
}
}
} |
package com.w3spoint; import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern; public class RegexTest {
private static final String PATTERN =
"([01]?[0-9]|2[0-3]):[0-5][0-9]";
public static void main(String args[]){
List<String> values = new ArrayList<String>();
values.add("05:00");
values.add("17:01");
values.add("24:00");
values.add("13:1");
Pattern pattern = Pattern.compile(PATTERN);
for (String value : values){
Matcher matcher = pattern.matcher(value);
if(matcher.matches()){
System.out.println("Time "+ value +" is valid 24Hours Format");
}else{
System.out.println("Time "+ value +" is invalid 24Hours Format");
}
}
}
}
Output
Time 05:00 is valid 24Hours Format
Time 17:01 is valid 24Hours Format
Time 24:00 is invalid 24Hours Format
Time 13:1 is invalid 24Hours Format |
Time 05:00 is valid 24Hours Format
Time 17:01 is valid 24Hours Format
Time 24:00 is invalid 24Hours Format
Time 13:1 is invalid 24Hours Format