DateTime TryParse - mapping '99' to 2099,

2020-03-15 05:27发布

Possible Duplicate:
DateTime.TryParse century control C#

I need to TryParse a string such as the following: "01/01/99" into a DateTime object, and I'm using something like this:

DateTime outDate;
if (DateTime.TryParseExact("01/01/99", "dd/MM/yy", null, System.Globalization.DateTimeStyles.None, out outDate))
{
     //Do stuff here
}

Of course, this date gets parsed as 01/01/1999, which is not what I want - I want it to parse as 2099. Is there an easy way to do this? Sadly modifying the data I'm parsing to include the full year is not an option.

2条回答
淡お忘
2楼-- · 2020-03-15 05:52

Taken from this answer, you can supply ParseExact() with a culture object. Suspect TryParseExact() would be the same:

CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.LCID);
ci.Calendar.TwoDigitYearMax = 2099;
//Parse the date using our custom culture.
DateTime dt = DateTime.ParseExact(input, "MMM-yy", ci);
查看更多
小情绪 Triste *
3楼-- · 2020-03-15 05:56

This is a regional setting. In Windows 7 you can edit in Control Panel > Clock, Language and Region > Region and Language. On the formats tab, hit the Advanced button and look under date.

Off the top off my head, I don't know of any way to pragmatically change this, but if you set it in control panel your app will then use it so long as you don't change the culture.

That said, you really need to go beat whoever is supplying you with this data with a heavy object. We should have eliminated this type of Y2K nonsense 12 years ago.

edit - dan04's comment link also has some options.

查看更多
登录 后发表回答