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

后端 未结 11 749
庸人自扰
庸人自扰 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:29
    /(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23):?(0|1|2|3|4|5)\d/
    

    :)

    0 讨论(0)
  • 2020-12-23 14:32

    To keep the colon optional and allow all valid times:

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

    Note that this assumes midnight will always be 0000 and never 2400.

    0 讨论(0)
  • 2020-12-23 14:32

    I don't think regex is the right solution for this problem. Sure, it COULD be done, but it just seems wrong.

    Make sure your string is four characters long, or 5 characters with a colon in the middle. Then, parse each side and make sure that the left side is less than 24 and the right hand is less than 60.

    The regex solution is just so much more complicated.

    0 讨论(0)
  • 2020-12-23 14:38

    This is perfect:

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

    Note: 12 Hr Clock Only

    For Times like:

    0:01- 12:59
    00:01 - 12:59
    
    0 讨论(0)
  • 2020-12-23 14:39

    This is the one I've just come up with:

    (^((2[0-4])|([01]?[0-9])):[0-5][0-9]$)|(^((1[0-2])|(0?[1-9])(:[0-5][0-9])?)[pa]m$)
    

    Accepts:

    2pm
    4:30am
    07:05am
    18:45
    6:19
    00:55
    

    does not accept 00:05am - I am not sure if there is such time as 0am

    If you feel that : is optional for 24h time format (military) - just add a question mark after it

    0 讨论(0)
提交回复
热议问题