使用TryParseExact进行FormatException

时间:2014-06-05 09:56:38

标签: 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.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

2 个答案:

答案 0 :(得分:1)

嗯匹配" 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));
}

答案 1 :(得分:1)

string time =“900”.PadLeft(4,'0');

如果值为0900,900,9或甚至为0,则上面的行将非常小心;)