简体   繁体   中英

Regular expression to validate valid time

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

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 */
}

如果您想允许使用AM 和 PM (可选且不敏感)的军用标准,那么您可能想尝试一下。

^(?:(?: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 expression which i found work the best for 24H format (HH:mm:ss):

private bool TimePatternValidation(string time)
    => new Regex(@"^(([0-1][0-9])|([2][0-3]))(:([0-5][0-9])){1,2}$").IsMatch(time);

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM