Regular expression for matching HH:MM time format
I want a regexp for matching time in HH:MM format. Here's what I have, and it works:
^[0-2][0-3]:[0-5][0-9]$
This matches everything from 00:00 to 23:59.
However, I want to change it so 0:00 and 1:00, etc are also matched as well as 00:00 and 01:30. I.e to make the leftmost digit optional, to match HH:MM as well as H:MM.
Any ideas how to make that change? I need this to work in javascript as well as php.
Solution 1:
Your original regular expression has flaws: it wouldn't match 04:00
for example.
This may work better:
^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$
Solution 2:
Regular Expressions for Time
-
HH:MM 12-hour format, optional leading 0
/^(0?[1-9]|1[0-2]):[0-5][0-9]$/
-
HH:MM 12-hour format, optional leading 0, mandatory meridiems (AM/PM)
/((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/
-
HH:MM 24-hour with leading 0
/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
-
HH:MM 24-hour format, optional leading 0
/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
-
HH:MM:SS 24-hour format with leading 0
/(?:[01]\d|2[0-3]):(?:[0-5]\d):(?:[0-5]\d)/
Reference and Demo