DateTime.TryParse()的问题

c#

我有一个"2/15/50"需要转换为日期时间格式的字符串,我正在使用以下代码:

DateTime.TryParse("2/15/50", out dt);

我得到的输出是: 02/15/1950 12:00:00 AM

预期的输出是: 02/15/2050 12:00:00 AM

有没有办法可以实现后者。欢迎使用其他功能的建议。我也尝试使用Convert.ToDateTime,它返回与 TryParse 相同的输出。

回答

这应该对你有用,

CultureInfo ci = new CultureInfo("en-US");
ci.Calendar.TwoDigitYearMax = 2099;
DateTime.TryParse("2/15/50", ci, System.Globalization.DateTimeStyles.None, out DateTime dt)

这是关于该方法的文档,ParseExact 允许您指定格式等
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-5.0

这里是我得到文化信息代码的地方
https://www.hanselman.com/blog/how-to-parse-string-dates-with-a-two-digit-year-and-split-on-the-right -世纪在-c

  • Updated to use datetime.Parse @AdarshRavi the code above should work now, changed it away from parseexact

以上是DateTime.TryParse()的问题的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>