Alex Rivera | Logout

Regular expression to validate valid time

Asked 2009-05-19T20:26:23.827
17

I need a regular expression to validate time.

Valid values would be from 0:00 to 23:59.

When the time is less than 10:00 it should also support one character numbers.

These are valid values:

  • 9:00
  • 09:00
Edit
Report

3 Answers

8

I don't want to steal anyone's hard work but this is exactly what you're looking for, apparently.

using System.Text.RegularExpressions;

public bool IsValidTime(string thetime)
{
    Regex checktime =
        new Regex(@"^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$");

    return checktime.IsMatch(thetime);
}
answered 2009-05-19T20:29:57.827
2

The regex ^(2[0-3]|[01]d)([:][0-5]d)$ should match 00:00 to 23:59. Don't know C# and hence can't give you the relevant code.

/RS

answered 2009-05-19T20:40:31.643
2

If you want to allow military and standard with the use of AM and PM (optional and insensitive), then you may want to give this a try.

^(?:(?:0?[1-9]|1[0-2]):[0-5][0-9]\s?(?:[AP][Mm]?|[ap][m]?)?|(?:00?|1[3-9]|2[0-3]):[0-5][0-9])$ 
answered 2012-07-05T20:19:19.040

Your Answer