Developer Toolbox

Regex: Time (HH:MM, 24-hour)

A 24-hour time with two digits for the hour and two for the minute. The hour is 00 to 19 or 20 to 23, the minute 00 to 59, so 24:00 and 12:60 fail.

Open in Regex Tester The pattern and every example below are filled in.

Pattern

^([01]\d|2[0-3]):[0-5]\d$

How it works

^
Start of the string.
([01]\d|2[0-3])
The hour: 00 to 19, or 20 to 23.
:
A colon.
[0-5]\d
The minute: 00 to 59.
$
End of the string.

Matches

  • 00:00
  • 09:30
  • 23:59

Doesn't match

  • 24:00
  • 9:30
  • 12:60
  • 12:5

In your language

JavaScript
/^([01]\d|2[0-3]):[0-5]\d$/

A literal; new RegExp(source, flags) builds the same from a string.

Python
re.compile(r"^([01]\d|2[0-3]):[0-5]\d$", re.ASCII)

A raw string, so backslashes reach re as written. re.ASCII keeps \d to 0-9, as in JavaScript (Python matches any Unicode digit otherwise). Use re.fullmatch to test a whole string.

Java
Pattern.compile("^([01]\\d|2[0-3]):[0-5]\\d$")

A normal string literal, so every backslash is doubled. matcher(s).matches() tests the whole string.

Go
regexp.MustCompile(`^([01]\d|2[0-3]):[0-5]\d$`)

A raw string in backticks. RE2 runs in linear time but has no lookaround and no backreferences.

PHP
preg_match('/^([01]\d|2[0-3]):[0-5]\d$/D', $input)

PCRE with / delimiters inside a single-quoted string. Without the D modifier, $ also matches before a final newline, so it is added to patterns that end in $.

C#
new Regex(@"^([01]\d|2[0-3]):[0-5]\d$", RegexOptions.ECMAScript)

A verbatim string: backslashes stay, a quote is doubled. RegexOptions.ECMAScript keeps \d to 0-9, as in JavaScript. $ also matches before a final newline; to reject one, end the pattern with \z instead.

Common mistakes

  • 24:00 for the end of a day

    Opening hours and some ISO 8601 data write 24:00 for the end of a day, as in 09:00-24:00. Add |24:00 to the alternatives if your data uses it.

  • Single-digit hours

    People type 9:30. Make the first digit optional with ([01]?\d|2[0-3]), or pad the input before matching.

  • Seconds

    For HH:MM:SS, add (:[0-5]\d)? before the $. A leap second (23:59:60) then still fails, which is usually what you want.