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
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
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(timeStr, out time))
{
/* use time or timeStr for your bidding */
}
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])$
Very late to the party but I created this Regex which I found work the best for 24H format (HH:mm:ss OR HH:mm OR H:mm:ss OR H:mm):
private bool TimePatternValidation(string time)
=> new Regex(@"^(([0-1]?[0-9])|([2][0-3]))(:([0-5][0-9])){1,2}$").IsMatch(time);
[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] (am|pm|AM|PM)$",
ErrorMessage = "Invalid Time.")]
Try this
Better!!!
public bool esvalida_la_hora(string thetime)
{
Regex checktime = new Regex("^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
if (!checktime.IsMatch(thetime))
return false;
if (thetime.Trim().Length < 5)
thetime = thetime = "0" + thetime;
string hh = thetime.Substring(0, 2);
string mm = thetime.Substring(3, 2);
int hh_i, mm_i;
if ((int.TryParse(hh, out hh_i)) && (int.TryParse(mm, out mm_i)))
{
if ((hh_i >= 0 && hh_i <= 23) && (mm_i >= 0 && mm_i <= 59))
{
return true;
}
}
return false;
}
public bool IsTimeString(string ts)
{
if (ts.Length == 5 && ts.Contains(':'))
{
int h;
int m;
return int.TryParse(ts.Substring(0, 2), out h)
&& int.TryParse(ts.Substring(3, 2), out m)
&& h >= 0 && h < 24
&& m >= 0 && m < 60;
}
else
return false;
}