C# DateTime.TryParse 让我很困惑

C# DateTime.TryParse makes me confused

我在我的程序中使用DateTime.TryParse方法来判断一个字符串值是否为DateTime,然后我注意到:

DateTime.TryParse("9.08", out DateTime dt)
// true
DateTime.TryParse("2.52", out DateTime dt)
// false

为什么会这样?

DateTime.TryParse是当前DateTimeFormatInfo对象中的解析信息,由当前线程文化隐式提供。

Because the DateTime.TryParse(String, DateTime) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results. If a specific date and time format will be parsed across different locales

在某些文化中,DateTime 分隔符是 . 而不是 /

在我的电脑上。

DateTime.TryParse 将 Parse "9.08" 今年 '09/08', 2018/09/08 是一个有效的 datetime, 所以它是 true.

DateTime.TryParse Parse "2.52" 是今年 '02/52',但是二月没有第 52 天,2018/02/52 不是有效的 DateTime, 所以它将是 false.

我会使用 DateTime.TryParseExact 来解析 DateTime,因为您可以将 CultureInfoParse DateTime 字符串设置为参数并确保符合您的预期格式。

DateTime.TryParseExact("09.08",
                       "MM.dd",
                        System.Globalization.CultureInfo.InvariantCulture,
                        System.Globalization.DateTimeStyles.None,
                        out dt);

根据 DateTime.TryParse 文档:

returns a value that indicates whether the conversion succeeded.

由于无法将 "2.52" 解析为任何有效日期,因此返回 false

除非你试图理解 .NET 的每次字符串转换 否则,你应该无法回答 "why exactly would that happened?"

DateTime.TryParse 只是一个简单的条件处理,以防止您在

时出错
Convert.ToDateTime(dateString)

因此,DateTime.TryParse = false 意味着您不应该对该字符串执行 Convert.ToDateTime

相反,如果字符串为DateTime.TryParse = true,则意味着该字符串应符合.NET 日期字符串的期望(这意味着.NET 知道如何将该字符串转换为DateTime)。