C# - System.FormatException:System.DateTime中的格式字符串无效

时间:2017-04-07 20:24:06

标签: c#

我正在比较日期格式,它适用于dd-MM-yyyy输入,但会引发dd/MM/yyyy的异常。

我的代码:

string s = Console.ReadLine();
DateTime d = DateTime.ParseExact(s, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string h = d.ToString("dd-MM-yyyy");
if (h.Equals(s))
{
    Console.WriteLine("Valid");
}
else
{
    Console.WriteLine("Invalid");
}

1 个答案:

答案 0 :(得分:2)

您已指定DateTime.ParseExact仅以"dd-MM-yyyy"格式预期日期。解析任何其他格式的日期字符串将抛出FormatException,因为它在Documentation中指定:

  

s 不包含日期和时间时,抛出FormatException   对应于格式中指定的模式。

如果您想支持多种格式,则应提供所有格式。这可能与接受格式数组的DateTime.ParseExact重载有关:

 var formats = new [] {"dd-MM-yyyy", "dd/MM/yyyy" };
 var d = DateTime.ParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)