Open In App

Validate a Time Format (HH:mm:ss) Using Regex in Java

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java Program to Validate the Pattern
// Using Regex
import java.util.regex.Pattern;
  
// Driver Class
public class GeeksForGeeks {
    
      // Regex Pattern
    private static final Pattern TIME_PATTERN
        = Pattern.compile("^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$");
  
      // Function to Validate time
    public static boolean validateTime(String timeString)
    {
        return TIME_PATTERN.matcher(timeString).matches();
    }
  
      // Main Function
    public static void main(String[] args)
    {
          // Replace with the time string
        // you want to check
        String timeToCheck = "18:35:40"
  
        if (validateTime(timeToCheck)) {
            // Proceed with time-related operations if valid
            System.out.println(
                timeToCheck + " is a valid time format.");
        }
        else {
            // Handle the invalid time case appropriately
            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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads