我想将输入的时间格式化为特定标准:
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
最佳答案
Hmm 匹配“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));
}
关于c# - 带有 TryParseExact 的 FormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24057063/