Regular Expressions Useful Regex Showcase Validate a 12hr and 24hr time string


Example

For a 12hour time format one can use:

^(?:0?[0-9]|1[0-2])[-:][0-5][0-9]\s*[ap]m$

Where

  • (?:0?[0-9]|1[0-2]) is the hour
  • [-:] is the separator, which can be adjusted to fit your need
  • [0-5][0-9] is the minute
  • \s*[ap]m followed any number of whitespace characters, and am or pm

If you need the seconds:

^(?:0?[0-9]|1[0-2])[-:][0-5][0-9][-:][0-5][0-9]\s*[ap]m$

For a 24hr time format:

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

Where:

  • (?:[01][0-9]|2[0-3]) is the hour
  • [-:h] the separator, which can be adjusted to fit your need
  • [0-5][0-9] is the minute

With the seconds:

^(?:[01][0-9]|2[0-3])[-:h][0-5][0-9][-:m][0-5][0-9]$

Where [-:m] is a second separator, replacing the h for hours with an m for minutes, and [0-5][0-9] is the second.