使用TryParseExact进行FormatException

Cag*_*man 5 c# format datetime

我想格式化一个特定标准的时间:

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));
}
Run Code Online (Sandbox Code Playgroud)

当用户键入它时:"09 00","0900","09:00","9 00","9:00"
但是当用户输入它时: "900"或者"9" 系统无法格式化,为什么?它们是我所采用的默认格式.

string str = CheckTime("09:00"); // works
str = CheckTime("900");          // FormatException at TryParseExact
Run Code Online (Sandbox Code Playgroud)

小智 1

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));
}
Run Code Online (Sandbox Code Playgroud)