C# DateTime.Parse 错误

C# DateTime.Parse Error

有人知道为什么会失败吗?我能够使用 ParseExact 解决它,但我想了解它失败的原因。

DateTime test = DateTime.Parse("Dec 24  17:45");

日期 < "Dec 24" 工作正常。日期 >= Dec 24 失败并出现此错误:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.

编辑: 感谢 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
    }
}

Dates < "Dec 24" work fine. Dates >= Dec 24 fail with this error

DateTime.Parse 使用 standard formats 来解析日期,它在 Day >= 24 时失败的原因是它正在考虑 那部分作为小时部分而不是日部分 如您所料。

由于允许的小时部分可以在 0 到 23 之间,因此它适用于那些 日期。 (不考虑一天部分)

它也忽略了 Dec 部分并考虑该部分的当前日期。

考虑下面的例子:

DateTime test = DateTime.Parse("Dec 22 17:45");

它returns:

test = {23/02/2015 10:17:00 PM}

看时间部分设置为22:17或10:17下午

您传递的日期时间格式无效。我认为问题在于您没有为日期部分提供年份。以下是可接受的日期时间示例:

DateTime time = DateTime.Parse("Dec 24 2015 17:45");