Validate that input is in this time format - "HH:MM"

Catfish picture Catfish · Oct 19, 2010 · Viewed 49.2k times · Source

I'm trying to use preg_match to validate that a time input is in this format - "HH:MM"

Answer

Charles picture Charles · Oct 19, 2010

You can use regular expressions to check that.

for 12-hour:

preg_match("/^(?:1[012]|0[0-9]):[0-5][0-9]$/", $foo)

for 24-hour:

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

If you use a 24-hour clock going from 01:00 to 24:59, use

preg_match("/^(?:2[0-4]|[01][1-9]|10):([0-5][0-9])$/", $foo)