Open In App

How to validate time in 24-hour format using Regular Expression

Last Updated : 26 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string str, the task is to check whether the string is valid time in 24-hour format or not by using Regular Expression

The valid time in the 24-hour format must satisfy the following conditions. 

  1. It should start from 0-23 or 00-23.
  2. It should be followed by a ‘:'(colon).
  3. It should be followed by two digits from 00 to 59.
  4. It should not end with ‘am’, ‘pm’ or ‘AM’, ‘PM’.

Examples: 

Input: str = “13:05” 
Output: true 
Explanation: The given string satisfies all the above mentioned conditions.

Input: str = “02:15” 
Output: true 
Explanation: The given string satisfies all the above mentioned conditions.

Input: str = “24:00” 
Output: false 
Explanation: The given string doesn’t be in the range of 0-23 or 00-23(i.e., hour is out of range), therefore it is not a valid time in 24-hour format.

Input: str = “10:60” 
Output: false 
Explanation: The given string doesn’t be in the range of 00 to 59(i.e., minute is out of range), therefore it is not a valid time in 24-hour format.

Input: str = “10:15 PM” 
Output: false 
Explanation: The given string end with ‘AM’ or ‘PM’, therefore it is not a valid time in 24-hour format. 

Approach: This problem can be solved by using Regular Expressions. 

  1. Get the string.
  2. Create a regular expression to check time in 24-hour format as mentioned below:  
regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]";

Where: 

  • ( represents the start of the group.
  • [01]?[0-9] represents the time that starts with 0-9, 1-9, 00-09, 10-19.
  • | represents or.
  • 2[0-3] represents the time starting with 20-23.
  • ) represents the end of the group. 
     
  • : represents the time that should be followed by a colon(:).
  • [0-5][0-9] represents the time followed by 00 to 59
  1. Match the given string with the regex, in Java, this can be done by using Pattern.matcher().
  2. Return true if the string matches with the given regex, else return false.

Below is the implementation of the above approach: 

C++




// C++ program to validate
// time in 24-hour format
// using Regular Expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate time in 24-hour format
bool isValidTime(string str)
{
 
  // Regex to check valid time in 24-hour format
  const regex pattern("([01]?[0-9]|2[0-3]):[0-5][0-9]");
 
  // If the time in 24-hour format
  // is empty return false
  if (str.empty())
  {
     return false;
  }
 
  // Return true if the time in 24-hour format
  // matched the ReGex
  if(regex_match(str, pattern))
  {
    return true;
  }
  else
  {
    return false;
  }
}
 
// Driver Code
int main()
{
   
  // Test Case 1:
  string str1 = "13:05";
  cout << str1 + ": "<< isValidTime(str1) << endl;
 
  // Test Case 2:
  string str2 = "02:15";
  cout << str2 + ": "<< isValidTime(str2) << endl;
 
  // Test Case 3:
  string str3 = "24:00";
  cout << str3 + ": "<< isValidTime(str3) << endl;
 
  // Test Case 4:
  string str4 = "10:60";
  cout << str4 + ": "<< isValidTime(str4) << endl;
 
  // Test Case 5:
  string str5 = "10:15 PM";
  cout << str5 + ": "<< isValidTime(str5) << endl;
 
  return 0;
}
 
// This code is contributed by yuvraj_chandra


Java




// Java program to validate the time in
// 24-hour format using Regular Expression.
 
import java.util.regex.*;
 
class GFG {
 
    // Function to validate the time in 24-hour format
    public static boolean isValidTime(String time)
    {
 
        // Regex to check valid time in 24-hour format.
        String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the time is empty
        // return false
        if (time == null) {
            return false;
        }
 
        // Pattern class contains matcher() method
        // to find matching between given time
        // and regular expression.
        Matcher m = p.matcher(time);
 
        // Return if the time
        // matched the ReGex
        return m.matches();
    }
 
    // Driver Code.
    public static void main(String args[])
    {
 
        // Test Case 1:
        String str1 = "13:05";
        System.out.println(str1 + ": "
                           + isValidTime(str1));
 
        // Test Case 2:
        String str2 = "02:15";
        System.out.println(str2 + ": "
                           + isValidTime(str2));
 
        // Test Case 3:
        String str3 = "24:00";
        System.out.println(str3 + ": "
                           + isValidTime(str3));
 
        // Test Case 4:
        String str4 = "10:60";
        System.out.println(str4 + ": "
                           + isValidTime(str4));
 
        // Test Case 5:
        String str5 = "10:15 PM";
        System.out.println(str5 + ": "
                           + isValidTime(str5));
    }
}


Python3




# Python3 program to validate the time in
# 24-hour format using Regular Expression.
import re
 
# Function to validate the time
# in 24-hour format
def isValidTime(time):
     
    # Regex to check valid time in 24-hour format.
    regex = "^([01]?[0-9]|2[0-3]):[0-5][0-9]$";
 
    # Compile the ReGex
    p = re.compile(regex);
 
    # If the time is empty
    # return false
    if (time == "") :
        return False;
         
    # Pattern class contains matcher() method
    # to find matching between given time
    # and regular expression.
    m = re.search(p, time);
     
    # Return True if the time
    # matched the ReGex otherwise False
    if m is None :
        return False;
    else :
        return True
         
# Driver Code.
if __name__ == "__main__" :
     
    # Test Case 1:
    str1 = "13:05";
    print(str1, ": ", isValidTime(str1));
 
    # Test Case 2:
    str2 = "02:15";
    print(str2, ": ", isValidTime(str2));
     
    # Test Case 3:
    str3 = "24:00";
    print(str3, ": ", isValidTime(str3));
     
    # Test Case 4:
    str4 = "10:60";
    print(str4, ": ", isValidTime(str4));
     
    # Test Case 5:
    str5 = "10:15 PM";
    print(str5, ": ", isValidTime(str5));
 
# This code is contributed by AnkitRai01


C#




// C# program to validate the
//  Time in 24-hour format
//using Regular Expressions
using System;
using System.Text.RegularExpressions;
class GFG
{
 
  // Main Method
  static void Main(string[] args)
  {
 
    // Input strings to Match
    // Time in 24-hour format
    string[] str={"13:05","02:15" ,"24:00","10:60","10:15 PM"};
    foreach(string s in str) {
      Console.WriteLine( isValidTime(s) ? "true" : "false");
    }
    Console.ReadKey(); }
 
  // method containing the regex
  public static bool isValidTime(string str)
  {
    string strRegex = @"^([01]?[0-9]|2[0-3]):[0-5][0-9]$";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(str))
      return (true);
    else
      return (false);
  }
}
 
// This code is contributed by Rahul Chauhan


Javascript




// Javascript program to validate the time in
// 24-hour format using Regular Expression.
 
// Function to validate the
// time in
// 24-hour format
function isValidTime(str) {
    // Regex to check valid
    // time in 24-hour format
    let regex = new RegExp(/^([01]\d|2[0-3]):?([0-5]\d)$/);
 
    //  if str
    // is empty return false
    if (str == null) {
        return "false";
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex.test(str) == true) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
let str1 = "13:05";
console.log(isValidTime(str1));
 
// Test Case 2:
let str2 = "02:15";
console.log(isValidTime(str2));
 
// Test Case 3:
let str3 = "24:00";
console.log(isValidTime(str3));
 
// Test Case 4:
let str4 = "10:60";
console.log(isValidTime(str4));
 
// Test Case 5:
let str5 = "10:15 PM";
console.log(isValidTime(str5));
 
// This code is contributed by Rahul Chauhan


Output: 

13:05: true
02:15: true
24:00: false
10:60: false
10:15 PM: false

 

Time Complexity: O(N) for each test case, where N is the length of the given string. 
Auxiliary Space: O(1)  



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads