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 li
This should do it:
^([01]\d|2[0-3]):?([0-5]\d)$
The expression reads:
^ Start of string (anchor)
( begin capturing group
[01] a "0" or "1"
\d any digit
| or
2[0-3] "2" followed by a character between 0 and 3 inclusive
) end capturing group
:? optional colon
( start capturing
[0-5] character between 0 and 5
\d digit
) end group
$ end of string anchor
I know this is an old question but here's a regex I came up with which seems to work.
^(([[0|1]\d)|(2[0-3]))[:]?([0-5]\d)$
You can edit it on this regex site
Edit I just realised that this answer ended up exactly the same as the accepted answer but I will leave it here at least for the value of the 'do it yourself' link
/^(?:[01]\d|2[0-3]):?[0-5]\d$/
Here is a better solution than the top one above for military plus a civilian solution.
Military
^(((([0-1][0-9])|(2[0-3])):?[0-5][0-9])|(24:?00))
I believe the or in the highest rated response is not properly parsing the subsets before and after without the extra set of parenthesis to group them. Also, I'm not certain that the \d
is just 0-9
in all iterations. It technically includes the special [[:digit:]]
although I've never dealt with that being an issue before. Any how, this should provide every thing including the crossover 2400/24:00
Civilian
^([0-9]|([1][0-2])):[0-5][0-9][[:space:]]?([ap][m]?|[AP][M]?)
This is a nice Civilian version that allows for the full range formatted like 12:30PM, 12:30P, 12:30pm, 12:30p, 12:30 PM, 12:30 P, 12:30 pm, or 12:30 p but requires the morning or post meridian characters to be the same case if both are included (no Am or pM).
I use both of these in a bit of JavaScript to validate time strings.
Remove the ':'
if the string has one, then if the string is of the form "DDDD"
, convert it into an int
and compare it to 2400.
Here's a blog post, looking for the same thing and a bunch of potential answers -- most of which don't work, but there is good discussion as to why each fails.
Of course, explicitly long and accurate is always a possibility!