C# TripArseExact的FormatException

C# TripArseExact的FormatException,c#,datetime,format,C#,Datetime,Format,我想将键入的时间格式化为特定标准: 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.Inv

我想将键入的时间格式化为特定标准:

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”,你必须给出两个数字

您可以通过以下方式更改用户输入:

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));
}
字符串时间=“900”。PadLeft(4,'0')


如果值为0900900,9甚至0,则应注意上述行)

H占位符也可以匹配两个数字,这是解析小时数>=10所必需的。所以900匹配H=90的Hmm。Kaboom.@HansPassant:但是
90
>24
,所以不需要将前两位数字视为小时。这是
TryParseExact
的限制吗?我想这与我最近提出的问题有一定的关系:我第一次看到这个问题时,立刻想到了@TimSchmelter。。在我看来,解析方法不知道它们在这种情况下会做什么。这也是一种可能性。我投了赞成票,但Xeijp answer当时为我解决了这个问题。