Validate a Time Format (HH:mm:ss) Using Regex in Java
Last Updated :
31 Jan, 2024
In this article, we will explore how to use regex to validate the used time format HH:mm:ss. Regular expressions (regex) offer a method, for validating time formats ensuring that they follow patterns which is mentioned below in the article.
How to Validate a Time Format (HH:mm:ss) Using Regex?
When testing a time string, against this pattern the regular expression engine tries to match each part of the pattern to its part, in the string. If the entire string perfectly matches the pattern, it is considered a time format in HH:mm:ss. If any part of the string does not follow the pattern, it is considered invalid.
Regex Pattern:
^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$
In the below example, we will check whether the given time “18:35:40” is valid or not:
Java
import java.util.regex.Pattern;
public class GeeksForGeeks {
private static final Pattern TIME_PATTERN
= Pattern.compile( "^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$" );
public static boolean validateTime(String timeString)
{
return TIME_PATTERN.matcher(timeString).matches();
}
public static void main(String[] args)
{
String timeToCheck = "18:35:40" ;
if (validateTime(timeToCheck)) {
System.out.println(
timeToCheck + " is a valid time format." );
}
else {
System.out.println(
timeToCheck
+ " is an invalid time format." );
}
}
}
|
Output
18:35:40 is a valid time format.
Explaination of the above Program:
In the above Program we are comparing the String with the mentioned regex. And the regex is explained below:
Matches the hour -> ^([0-1][0-9]|2[0-3])
- ^ Matches the beginning of the string.
- [0-1][0-9] Matches numbers 00 to 19.
- | Signifies “or”.
- 2[0-3] Matches numbers 20 to 23.
Matches the minutes -> : [0-5][0-9]
- : Matches a literal colon
- [0-5][0-9] Matches numbers 00 to 59
Matches the seconds -> :[0-5][0-9]$
- : Matches a literal colon.
- [0-5][0-9] Matches numbers 00 to 59.
- $ dollar sign indicates ending of the string.
Share your thoughts in the comments
Please Login to comment...