Time Validation Regular Expression
Time validation requires handling both 24-hour and 12-hour formats. The 24-hour format (also known as military time) follows the ISO 8601 standard, while the 12-hour format with AM/PM is commonly used in everyday contexts, particularly in the United States. For complete datetime validation, combine this with date validation.
24-Hour Format (HH:MM or HH:MM:SS)
This pattern validates time in 24-hour format, ranging from 00:00 to 23:59, with optional seconds.
Explanation
^- Start of the string.(?:[01]\d|2[0-3])- Hours: 00-09, 10-19 (using [01]\\d) or 20-23 (using 2[0-3]).:- Colon separator.[0-5]\d- Minutes: 00-59.(?::[0-5]\d)?- Optional seconds: colon followed by 00-59. The ? makes the entire group optional.$- End of the string.
Implementation
Test Cases
| Time | Valid |
|---|---|
| 00:00 | |
| 00:00:00 | |
| 09:30 | |
| 09:30:45 | |
| 12:00 | |
| 12:00:00 | |
| 23:59 | |
| 23:59:59 | |
| 13:45:30 | |
| 00:59:59 | |
| 24:00 | |
| 25:00 | |
| 12:60 | |
| 12:30:60 | |
| 9:30 | |
| 09:5 | |
| 9:5 | |
| 12:00 PM | |
| 1200 | |
| 12: | |
| :30 | |
| 12:30:5 | |
| (empty string) |
12-Hour Format with AM/PM
This pattern validates time in 12-hour format with AM/PM designation. It accepts hours from 1-12, minutes from 00-59, optional seconds, and either AM or PM (case-insensitive). The space before AM/PM is optional.
Explanation
^- Start of the string.(?:0?[1-9]|1[0-2])- Hours: 1-9 (with optional leading zero using 0?[1-9]) or 10-12 (using 1[0-2]).:- Colon separator.[0-5]\d- Minutes: 00-59.(?::[0-5]\d)?- Optional seconds: colon followed by 00-59.\s?- Optional whitespace before AM/PM.[AaPp][Mm]- AM or PM in any case combination (AM, am, PM, pm, etc.).$- End of the string.
Implementation
Test Cases
| Time | Valid |
|---|---|
| 12:00 AM | |
| 12:00 PM | |
| 1:00 AM | |
| 1:00 PM | |
| 01:00 AM | |
| 01:00 PM | |
| 9:30 AM | |
| 09:30 PM | |
| 12:59 AM | |
| 11:59 PM | |
| 12:00:00 AM | |
| 11:59:59 PM | |
| 1:30:45 PM | |
| 12:00AM | |
| 12:00PM | |
| 12:00 am | |
| 12:00 pm | |
| 00:00 AM | |
| 13:00 PM | |
| 12:60 PM | |
| 12:30:60 AM | |
| 12:00 | |
| 9:5 AM | |
| 12:00 XM | |
| 25:00 PM | |
| (empty string) |