2014-06-05 51 views
5

我想格式化的时间输入到一个特定的标准:出现FormatException与TryParseExact

private String CheckTime(String value) 
{ 
    String[] formats = { "HH mm", "HHmm", "HH:mm", "H mm", "Hmm", "H:mm", "H" }; 
    DateTime expexteddate; 
    if (DateTime.TryParseExact(value, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out expexteddate)) 
     return expexteddate.ToString("HH:mm"); 
    else 
     throw new Exception(String.Format("Not valid time inserted, enter time like: {0}HHmm", Environment.NewLine)); 
} 

当用户键入想: “09 00”, “0900”, “09:00”,“9 00“,”9:00“
但是当用户输入类似于:"900""9"系统无法格式化它,为什么? 他们是我默认的格式。

string str = CheckTime("09:00"); // works 
str = CheckTime("900");   // FormatException at TryParseExact 
+0

为H占位符可以匹配两个数字,以及,必要以解析小时> = 10所以900匹配嗯用H = 90. Kaboom。 –

+0

@HansPassant:但'90'是'> 24',所以不需要将前两位数字视为小时。这是'TryParseExact'的限制吗?我认为这是某种程度上与我最近问自己的问题有关:http://stackoverflow.com/questions/21902722/datetime-parseexact-with-7-digits-one-or-two-digit-month –

+0

第一次我看到这个问题,立即@TimSchmelter [问题](http://stackoverflow.com/q/21902722/447156)也出现在我的脑海里。在我看来,解析方法并不知道他们在这样做案例.. –

回答

1

嗯匹配“0900”和H匹配“09”你必须给2位数。

可以只是改变用户输入这种方式:

private String CheckTime(String value) 
{ 
    // change user input into valid format 
    if(System.Text.RegularExpressions.Regex.IsMatch(value, "(^\\d$)|(^\\d{3}$)")) 
     value = "0"+value; 

    String[] formats = { "HH mm", "HHmm", "HH:mm", "H mm", "Hmm", "H:mm", "H" }; 
    DateTime expexteddate; 
    if (DateTime.TryParseExact(value, formats, System.Globalization.CultureInfo.InvariantCulture,  System.Globalization.DateTimeStyles.None, out expexteddate)) 
     return expexteddate.ToString("HH:mm"); 
    else 
     throw new Exception(String.Format("Not valid time inserted, enter time like:  {0}HHmm", Environment.NewLine)); 
} 
+0

那么做的窍门:-) – Cageman

1

串时间= “900” .PadLeft(4, '0');

上面的行会照顾,如果值是0900,900,9或甚至0)

+0

这也是一个可操作性。来自我的投票,但Xeijp回答当时解决了我的问题。 – Cageman

相关问题