2009-05-19 34 views
14

有人可以帮我建立一个正则表达式来验证时间吗?正则表达式来验证有效时间

有效值从0:00到23:59。

当时间不到10:00,也应该支持一个字符数

即:这些都是有效的值:

  • 9:00
  • 09:00

谢谢

+0

对不起,我输错,我想第一个数字来支持1个字符。即:2:00和02:00 – juan 2009-05-19 20:41:42

+0

是'00:00`,'01:00`,...有效值吗? – Gumbo 2009-05-19 20:44:20

+0

是的,但也是0:00和1:00 – juan 2009-05-19 20:46:30

回答

38

试试这个正则表达式:

^(?:[01]?[0-9]|2[0-3]):[0-5][0-9]$ 

或更明显:

^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$ 
7

我不想偷任何人的辛勤工作,但this是你在寻找什么,显然。

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

正则表达式^(2[0-3]|[01]d)([:][0-5]d)$应该匹配00:00到23:59。不知道C#,因此不能给你相关的代码。

/RS

7

我只是使用DateTime.TryParse()。

DateTime time; 
string timeStr = "23:00" 

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

如果你想允许军事标准配合使用上午和下午(可选和不敏感的),那么你可能想试试这个。

^(?:(?: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

更好!!!

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; 
    } 
-1
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
[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] (am|pm|AM|PM)$", 
        ErrorMessage = "Invalid Time.")] 

试一下这个