gpt4 book ai didi

C# DateTime.TryParse 让我很困惑

转载 作者:行者123 更新时间:2023-11-30 13:35:32 24 4
gpt4 key购买 nike

我在我的程序中使用 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 将解析 "9.08" 今年是 '09/08', 2018/09/08 是一个有效的 datetime,所以它是 true

DateTime.TryParse 将解析 "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);

关于C# DateTime.TryParse 让我很困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51472531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com