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
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
juan
  • 80,295
  • 52
  • 162
  • 195

9 Answers9

46

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
  • 643,351
  • 109
  • 780
  • 844
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);
}
Nick Presta
  • 28,134
  • 6
  • 57
  • 76
  • I don't understand why this has gotten upvotes when it doesn't work. Those three `d` characters will only match the literal character `d`, so this returns `false` for `"00:00"` and `"23:59"` but returns `true` for `"0d:0d"`. They should instead be [``\d``](https://docs.microsoft.com/dotnet/standard/base-types/character-classes-in-regular-expressions#decimal-digit-character-d) or `[0-9]` to match any decimal digit. The next line of that blog entry, which is absent from this answer, is "**Time regular expression** used to control time is `^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$`". – Lance U. Matthews Dec 02 '21 at 06:42
8

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 */
}
cdonner
  • 37,019
  • 22
  • 105
  • 153
scottm
  • 27,829
  • 22
  • 107
  • 159
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])$ 
roydukkey
  • 3,149
  • 2
  • 27
  • 43
2

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);
  • As you noted, this matches the `HH:mm:ss` format, which was not requested by the question, yet fails to match the `H:mm` format, which _was_ requested by the question. – Lance U. Matthews Dec 02 '21 at 06:51
  • You right, i fixed it. Now it work on every time pattern (HH:mm:ss | H:mm:ss | HH:mm | H:mm) –  Dec 06 '21 at 06:16
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

Dave New
  • 38,496
  • 59
  • 215
  • 394
user40552
  • 151
  • 3
1
[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] (am|pm|AM|PM)$", 
                   ErrorMessage = "Invalid Time.")]

Try this

quadroid
  • 8,444
  • 6
  • 49
  • 82
  • 3
    Why should the OP "try this"? A **good answer** will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer. – Maximilian Ast Jul 27 '16 at 10:42
0

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