任何人都知道为什么会失败?我能够使用ParseExact解决它,但我想理解为什么它失败了.
DateTime test = DateTime.Parse("Dec 24 17:45");
Run Code Online (Sandbox Code Playgroud)
日期<"12月24日"工作正常.日期> = 12月24日因此错误失败:
mscorlib.dll中出现未处理的"System.FormatException"类型异常附加信息:日历System.Globalization.GregorianCalendar中不支持字符串表示的DateTime.
编辑:感谢Habib注意到即使我没有收到错误,也不是我期待的结果.所以当不使用支持的格式时要小心DateTime.Parse!
这是我为解决这个问题所做的工作.我只需要处理两种不同的格式.今年将是"MMM dd HH:mm"否则将是"MMM dd yyyy"
if (!DateTime.TryParseExact(inDateTime, "MMM dd HH:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces,out outDateTime))
{
if (!DateTime.TryParseExact(inDateTime, "MMM dd yyyy", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out outDateTime))
{
//Handle failure to Parse
}
}
Run Code Online (Sandbox Code Playgroud)