2009-05-19 30 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.")] 

試一下這個