Regex for Time (HH:MM) — Pattern Explained with Examples
This regex validates time strings in both 24-hour and 12-hour formats. The 24-hour pattern accepts 00:00 through 23:59, while the 12-hour pattern accepts 01:00 through 12:59 with AM/PM suffix. These patterns are essential for scheduling applications, booking systems, and log parsing.
The Pattern
24-hour format:
/^([01]\d|2[0-3]):([0-5]\d)$/12-hour format:
/^(0[1-9]|1[0-2]):([0-5]\d)\s?[APap][Mm]$/Pattern Breakdown
24-hour
| Part | Meaning |
|---|---|
^ | Start of string |
([01]\d|2[0-3]) | Hour: 00–19 or 20–23 |
: | Literal colon separator |
([0-5]\d) | Minute: 00–59 |
$ | End of string |
12-hour
| Part | Meaning |
|---|---|
^ | Start of string |
(0[1-9]|1[0-2]) | Hour: 01–12 |
: | Literal colon separator |
([0-5]\d) | Minute: 00–59 |
\s? | Optional space |
[APap][Mm] | AM or PM (case-insensitive) |
$ | End of string |
Matches
14:30(24h)09:00(24h)23:59(24h)12:00 AM(12h)11:59 PM(12h)01:05am(12h, no space)
Does NOT Match
24:00— hour 24 is invalid12:60— minute 60 is invalid9:00— missing leading zero (24h)25:00— hour exceeds 2413:00 PM— 13 is not a valid 12-hour hour00:00 AM— 00 is not valid in 12-hour format12:00(without AM/PM) — ambiguous, 12h pattern requires AM/PM
Language Examples
JavaScript
const time24 = /^([01]\d|2[0-3]):([0-5]\d)$/;
const time12 = /^(0[1-9]|1[0-2]):([0-5]\d)\s?[APap][Mm]$/;
console.log(time24.test('14:30')); // true
console.log(time24.test('24:00')); // false
console.log(time12.test('12:00 AM')); // true
console.log(time12.test('13:00 PM')); // false
// Combine both formats
const timeRegex = /^(([01]\d|2[0-3]):([0-5]\d)|(0[1-9]|1[0-2]):([0-5]\d)\s?[APap][Mm])$/;Python
import re
time24 = r'^([01]\d|2[0-3]):([0-5]\d)$'
time12 = r'^(0[1-9]|1[0-2]):([0-5]\d)\s?[APap][Mm]$'
print(bool(re.match(time24, '14:30'))) # True
print(bool(re.match(time24, '24:00'))) # False
print(bool(re.match(time12, '12:00 AM'))) # True
print(bool(re.match(time12, '00:00 AM'))) # FalseCommon Pitfalls
24:00 vs 00:00 —
24:00is technically valid in some standards (end of day) but most applications expect00:00for midnight. Choose based on your domain.AM/PM with 12 —
12:00 AMis midnight and12:00 PMis noon. Many users get this wrong. Consider using 24-hour format internally to avoid ambiguity.Optional seconds — Neither pattern includes seconds (
:SS). If you need seconds, append(:[0-5]\d)?before the end anchor.
Real-World Use Cases
- Appointment booking — Validating time slot inputs in scheduling systems
- Log parsing — Extracting timestamps from server or application logs
- Clock widgets — Displaying and validating user-configured time formats
FAQ
Related Patterns
- Regex for ISO 8601 Date/Time
- Regex for Date (YYYY-MM-DD)
- Regex for Password Strength
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro