DateTime string parsing

社会主义新天地 提交于 2019-11-29 04:03:43

Theoretically elegant way of doing this: change the TwoDigitYearMax property of the Calendar used by the DateTimeFormatInfo you're using to parse the text. For instance:

CultureInfo current = CultureInfo.CurrentCulture;
DateTimeFormatInfo dtfi = (DateTimeFormatInfo) current.DateTimeFormat.Clone();
// I'm not *sure* whether this is necessary
dtfi.Calendar = (Calendar) dtfi.Calendar.Clone();
dtfi.Calendar.TwoDigitYearMax = 1910;

Then use dtfi in your call to DateTime.ParseExact.

Practical way of doing this: add "20" to the start of your input, and parse with "yyyyMMdd".

Well, if you're definite that all your source dates are this century, then you could use parseExact against a "20"-prefixed source string.

You will need to determine some kind of threshold date appropriate for your data. If the parsed date is before this date, add 100 years. A safe way to do that is to prefix the input string with the appropriate century. In this example I've chosen 1970 as the cutoff:

string input = ...;
DateTime myDate;

if (Convert.ToInt32(input.Substring(0, 2)) < 70)
    myDate = DateTime.ParseExact("20" + input, ...);
else
    myDate = DateTime.ParseExact("19" + input, ...); 

Jon Skeet also posted a nice example using DateTimeFormatInfo that I had momentarily forgotten about :)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!