Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for HH:MM:SS

I have a reqular expression that matches HH:MM e.g. 12:23 and it is:

function IsValidTime(timeString)
{
    var pattern = /^\d?\d:\d{2}$/;
    if (!timeString.match(pattern))
        return false;
}

How do I change this line:

var pattern = /^\d?\d:\d{2}$/;

to check for a string that is formatted with seconds like so: HH:MM:SS e.g. 12:23:05

like image 440
user1646528 Avatar asked Aug 22 '26 13:08

user1646528


2 Answers

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

for 24-hour time, leading zeroes mandatory.

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

for 24-hour time, leading zeroes optional.

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

for 12-hour time, leading zeroes mandatory.

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

for 12-hour time, leading zeroes optional.

like image 196
Tim Pietzcker Avatar answered Aug 25 '26 01:08

Tim Pietzcker


Something as simple as the following should work:

/([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]/g

Regex Explanation:

  • ([01][0-9]|2[0-3])
    • A collection of the following:
    • [01][0-9] the characters "0" or "1" followed by any digit between 0 and 9
    • | - or
    • 2[0-3] the character "2" followed by a digit between 0 and 3
  • : a literal colon
  • [0-5][0-9] - any digit between 0 to 5 followed by any digit between 0 and 9
  • : a literal colon
  • [0-5][0-9] - any digit between 0 to 5 followed by any digit between 0 and 9

Demo:

Regex101

like image 38
h2ooooooo Avatar answered Aug 25 '26 02:08

h2ooooooo