Regular expression to validate valid time

后端 未结 8 1643
余生分开走
余生分开走 2020-12-03 14:24

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 su

相关标签:
8条回答
  • 2020-12-03 14:43

    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);
    }
    
    0 讨论(0)
  • 2020-12-03 14:46

    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])$ 
    
    0 讨论(0)
  • 2020-12-03 14:46
        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;
        }
    
    0 讨论(0)
  • 2020-12-03 14:56

    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

    0 讨论(0)
  • 2020-12-03 14:59

    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 讨论(0)
  • 2020-12-03 15:00

    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 */
    }
    
    0 讨论(0)
提交回复
热议问题