4.6. Validate Traditional Time Formats
Problem
You want to validate times in various traditional time formats, such as hh:mm and hh:mm:ss in both 12-hour and 24-hour formats.
Solution
Hours and minutes, 12-hour clock:
^(1[0-2]|0?[1-9]):([0-5]?[0-9])(●?[AP]M)?$| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Hours and minutes, 24-hour clock:
^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$
| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Hours, minutes, and seconds, 12-hour clock:
^(1[0-2]|0?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])(●?[AP]M)?$| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Hours, minutes, and seconds, 24-hour clock:
^(2[0-3]|[01]?[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$
| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
The question marks in all of the preceding regular expressions make leading zeros optional. Remove the question marks to make leading zeros mandatory.
Discussion
Validating times is considerably easier than validating dates.
Every hour has 60 minutes, and every minute has 60 seconds. This means
we don’t need any complicated alternations in the regex. For the minutes
and seconds, we don’t use alternation at all. ‹[0-5]?[0-9]› matches a digit between 0 and 5, followed by a digit between 0 and 9. This correctly matches any number between 0 and 59. The question mark after the first character class makes it optional. This way, a single digit between 0 and 9 is ...