我想将输入的时间格式化为特定的标准:
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发布于 2014-06-05 10:25:10
嗯,匹配"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));
}发布于 2017-03-09 09:40:47
字符串时间= "900".PadLeft(4,'0');
如果值为0900,900,9,甚至0,请注意上面的行;)
https://stackoverflow.com/questions/24057063
复制相似问题