Validate a time string (12h and 24h) in JavaScript
Intermediate · 3 min read
Times show up in forms all the time: an alarm app, a booking slot, a bus departure, an "opening hours" field. People write them in two styles. The 24-hour clock says 23:59. The 12-hour clock says 11:59 pm. In this tutorial you will write a check for both, with optional seconds, and then pull the hour and minute out as numbers.
The interesting part is the hour. \d\d happily accepts 24 and 99, so you will learn how to describe a number range in a pattern. You need to know /.../.test(), ^, $ and \d. Groups and flags are explained as we go.
The rules
- 24-hour: hours
00to23, minutes00to59, optional seconds00to59. Always two digits each. - 12-hour: hours
1to12(a leading zero is fine), minutes and optional seconds as above, thenamorpm, with or without a space. There is no hour0or13, so midnight is12:00 AM.
Ranges by shape
A character class like [0-5] matches one digit from 0 to 5. That is enough for minutes: the first digit is 0 to 5 and the second is anything, [0-5]\d.
Hours 00 to 23 don't fit one pattern like that, because the second digit depends on the first. So split them and join with | ("or"):
[01]\d 00 to 19
2[0-3] 20 to 23
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
11 Is the value a time?
fairCheck whether a string is a valid time. Handle 24-hour and 12-hour forms, and optional seconds.
Stuck? Three hints, smallest first
- 1. Hours 0–23 is
([01]\d|2[0-3]). Minutes are[0-5]\d. - 2. Make seconds optional with a group:
(:[0-5]\d)?. - 3. 12-hour clocks run 1–12, and
00:30 amis not a time.
Step 1: the wrong turn
The first attempt usually treats every part as two digits:
const loose = /^\d\d:\d\d$/;
console.log(loose.test('09:05')); // true
console.log(loose.test('24:00')); // true, but there is no hour 24
console.log(loose.test('12:60')); // true, but there is no minute 60
Step 2: the 24-hour pattern
Use the hour pieces from above inside a group, and [0-5]\d for the minutes:
const TIME_24 = /^([01]\d|2[0-3]):[0-5]\d$/;
console.log(TIME_24.test('00:00')); // true
console.log(TIME_24.test('23:59')); // true
console.log(TIME_24.test('24:00')); // false
console.log(TIME_24.test('12:60')); // false
console.log(TIME_24.test('9:05')); // false
The brackets around [01]\d|2[0-3] matter. Without them, the | would split the whole pattern into two halves. 9:05 is refused because the 24-hour form always has two hour digits.
Step 3: optional seconds
Wrap : and the seconds in a group and put ? after it, which means "this group may appear once or not at all":
const TIME_24 = /^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;
console.log(TIME_24.test('23:59:59')); // true
console.log(TIME_24.test('23:59')); // true
console.log(TIME_24.test('09:05:')); // false
A colon with no seconds after it doesn't match the group, and then $ fails because a character is left over.
Step 4: the 12-hour pattern
Hours 1 to 12 split into two pieces again: 0?[1-9] is 1 to 9 with an optional leading zero, and 1[0-2] is 10 to 12. Then \s? allows an optional space, and ([ap]m) is "am" or "pm". The i flag at the end makes it accept AM and PM too:
const TIME_12 = /^(0?[1-9]|1[0-2]):[0-5]\d(:[0-5]\d)?\s?([ap]m)$/i;
console.log(TIME_12.test('1:05 pm')); // true
console.log(TIME_12.test('1:05pm')); // true
console.log(TIME_12.test('12:00 AM')); // true
console.log(TIME_12.test('13:00 pm')); // false
console.log(TIME_12.test('00:30 am')); // false
console.log(TIME_12.test('1:05')); // false: am or pm is required
Then isTime accepts either form:
const TIME_24 = /^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;
const TIME_12 = /^(0?[1-9]|1[0-2]):[0-5]\d(:[0-5]\d)?\s?([ap]m)$/i;
const isTime = (value) => TIME_24.test(value) || TIME_12.test(value);
console.log(isTime('23:59'), isTime('1:05 pm'), isTime('9')); // true true false
Step 5: get the parts out
A yes or no is often not enough. You want the hour and minute as numbers. Named groups, (?<hour>...), label each part. exec returns the match, or null if there is none. (?:...) is a group that bundles without capturing, so only the three named parts are kept:
const PARTS = /^(?<hour>[01]\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?$/;
function parseTime(value) {
const m = PARTS.exec(value);
if (!m) return null;
const { hour, minute, second } = m.groups;
return { hour: Number(hour), minute: Number(minute), second: Number(second ?? 0) };
}
console.log(parseTime('23:59:59')); // { hour: 23, minute: 59, second: 59 }
console.log(parseTime('09:05')); // { hour: 9, minute: 5, second: 0 }
console.log(parseTime('24:00')); // null
When there are no seconds, the second group is undefined, and second ?? 0 turns that into 0.
The full solution
The panel runs a list of times through both patterns and isTime, then parses two of them. Press Run and look at how 24:00, 00:30 am and 13:00 pm are refused.
// 24-hour, with optional seconds.
const TIME_24 = /^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;
// 12-hour, 1 to 12, with a required am or pm.
const TIME_12 = /^(0?[1-9]|1[0-2]):[0-5]\d(:[0-5]\d)?\s?([ap]m)$/i;
const isTime = (value) => TIME_24.test(value) || TIME_12.test(value);
// Named groups make the parts usable, not just testable.
const PARTS = /^(?<hour>[01]\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?$/;
function parseTime(value) {
const m = PARTS.exec(value);
if (!m) return null;
const { hour, minute, second } = m.groups;
return { hour: Number(hour), minute: Number(minute), second: Number(second ?? 0) };
}
const cases = ['00:00', '09:05', '23:59', '23:59:59', '24:00', '12:60', '9:05',
'1:05 pm', '12:00 AM', '13:00 pm', '00:30 am', '', '9', '09:05:'];
for (const t of cases) {
console.log(JSON.stringify(t).padEnd(12), '24h:', String(TIME_24.test(t)).padEnd(6),
'12h:', String(TIME_12.test(t)).padEnd(6), 'either:', isTime(t));
}
console.log('parsed 23:59:59 ->', parseTime('23:59:59'));
console.log('parsed 09:05 ->', parseTime('09:05'), '<- seconds default to 0');
Output
20 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 20 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('midnight', TIME_24.test('00:00'), true);
test('a padded morning time', TIME_24.test('09:05'), true);
test('one minute to midnight', TIME_24.test('23:59'), true);
test('with seconds', TIME_24.test('23:59:59'), true);
test('24:00 is not a valid hour', TIME_24.test('24:00'), false);
test('nor is minute 60', TIME_24.test('12:60'), false);
test('an unpadded hour is refused by the 24-hour pattern', TIME_24.test('9:05'), false);
test('a trailing colon is refused', TIME_24.test('09:05:'), false);
test('an empty string is refused', isTime(''), false);
test('a bare number is refused', isTime('9'), false);
test('a 12-hour time with pm passes', TIME_12.test('1:05 pm'), true);
test('and is case-insensitive', TIME_12.test('12:00 AM'), true);
test('no space is fine too', TIME_12.test('1:05pm'), true);
test('13 is not a 12-hour hour', TIME_12.test('13:00 pm'), false);
test('nor is 00', TIME_12.test('00:30 am'), false);
test('a 12-hour time without am or pm is refused', TIME_12.test('1:05'), false);
test('either form is accepted by isTime', ['23:59', '1:05 pm'].every(isTime), true);
test('the parts are extracted as numbers', parseTime('23:59:59'), { hour: 23, minute: 59, second: 59 });
test('missing seconds default to zero', parseTime('09:05'), { hour: 9, minute: 5, second: 0 });
test('and an invalid time parses to null', parseTime('24:00'), null);
The hour is the interesting part: ([01]d|2[0-3]) rather than d{2}, because the range 00–23 does not fit a single character class. That is the same technique as the IP octet — a numeric range in a regex has to be spelled out by shape.
The 12-hour pattern makes a different mistake possible. Its hours run 1–12, so 00:30 am is invalid, and midnight is written 12:00 AM. Both are asserted, because a pattern reused from the 24-hour case would quietly accept the wrong set.
exec with named groups gives you the parts as well as a yes or no, which is usually what you actually wanted. If you are heading towards arithmetic on times, though, stop here: validate the shape, then convert to minutes-since-midnight or a real date, and do the comparisons there.
Common mistakes
- Using
\d\dfor the hour. It allows 24 to 99. Spell the range out as[01]\d|2[0-3]. - Forgetting the group around the
|.^[01]\d|2[0-3]:...$means "starts with 00 to 19" or "the rest", which matches far too much. - Reusing the 24-hour hours for the 12-hour clock. A 12-hour clock has no
00and no13.
Try it yourself
- Write
toMinutes(value)that usesparseTimeand returns minutes since midnight, so'01:30'gives 90. - Change
TIME_24to also accept a single-digit hour like9:05. (Hint: make the first hour digit optional, carefully.) - Write
to24h('1:05 pm')that returns'13:05'.