tags:

views:

838

answers:

6

Can someone help me build 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

ie: these are valid values:

  • 9:00
  • 09:00

Thanks

+11  A: 

Try this regular expression:

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

Or to be more distinct:

^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
Gumbo
sorry, i meant 0:00 (fixed the question). +1 though
Juan Manuel
Nicely done. +1
Michael Myers
+2  A: 

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);
}
Nick Presta
A: 
[0-2][0-9]:[0-5][0-9]
Tim Hoolihan
This allows up to 29:59.
Michael Myers
A: 

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

Non-capturing.

steamer25
A: 

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

+2  A: 

I'd just use DateTime.TryParse().

DateTime time;
string timeStr = "23:00"

if(DateTime.TryParse(out time))
{
  /* use time or timeStr for your bidding */
}
scottm
It's for Client-Side validation
Juan Manuel