我正在比较日期格式,它适用于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");
}
答案 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)