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
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:
Thanks
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]$
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);
}
I'd just use DateTime.TryParse().
DateTime time;
string timeStr = "23:00"
if(DateTime.TryParse(out time))
{
/* use time or timeStr for your bidding */
}