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

后端 未结 11 784
庸人自扰
庸人自扰 2020-12-23 13:44

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

11条回答
  •  长情又很酷
    2020-12-23 14:24

    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.

提交回复
热议问题