我想格式化的时间输入到一个特定的标准:出现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
为H占位符可以匹配两个数字,以及,必要以解析小时> = 10所以900匹配嗯用H = 90. Kaboom。 –
@HansPassant:但'90'是'> 24',所以不需要将前两位数字视为小时。这是'TryParseExact'的限制吗?我认为这是某种程度上与我最近问自己的问题有关:http://stackoverflow.com/questions/21902722/datetime-parseexact-with-7-digits-one-or-two-digit-month –
第一次我看到这个问题,立即@TimSchmelter [问题](http://stackoverflow.com/q/21902722/447156)也出现在我的脑海里。在我看来,解析方法并不知道他们在这样做案例.. –