Regular expression to validate valid time

I'd just use DateTime.TryParse().

DateTime time;
string timeStr = "23:00"

if(DateTime.TryParse(timeStr, out time))
{
  /* use time or timeStr for your bidding */
}

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);
}

Tags:

C#

.Net

Regex