Regular expression for matching time in military (24 hour) format

Viewed 53216

I would like a JavaScript regular expression that will match time using the 24 hour clock, where the time is given with or without the colon.

For example, I would like to match time in the following formats:

  • 0800
  • 23:45
  • 2345

but that would not match invalid times such as

  • 34:68
  • 5672
14 Answers

A human friendly version:

^([0-1][0-9]|2[0-3]):?([0-5][0-9])$

I've done this slightly differently to avoid the possibility of a single zero leading the time, like 0:45 vs 00:45. From what I can see, the more commonly used format allows for this technically incorrect format. Mine also prevents pattern matches in trailing characters, as others have done.

\b^(0?[1-9]|[0-1][0-9]|2[0-3]):([0-5][0-9])(:[0-5][0-9])?$

This regex will also pass for when leading zero is not there. Example: 1:11:11

(0?[0-9]|[0-1][0-9]|2[0-3]):([0-5]\d):([0-5]\d))
Related