DateTime字符串解析
我已经为解析ascii文件做了一个通用的解析器。 当我想解析日期时,我使用DateTime对象中的ParseExact函数来解析,但是我遇到了年份的问题。
要解析的文本是“090812”,其中parseExact字符串为“yyMMdd”。
我希望得到一个DateTime对象说“12 / 8-2009”,但我得到“12 / 8-1909”。 我知道,我可以通过以后解析它来制作一个丑陋的解决方案,从而修改年份..
有谁知道解决这个问题的聪明方法?
提前致谢..
索伦
理论上优雅的方法:更改您用于解析文本的DateTimeFormatInfo
使用的Calendar
的TwoDigitYearMax
属性。 例如:
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;
然后在调用DateTime.ParseExact
使用dtfi
。
实际操作方法:在输入开头添加“20”,并用“yyyyMMdd”解析。
好吧,如果您确定所有源日期都是本世纪,那么您可以使用parseExact来对应“20”前缀的源字符串。
您需要确定适合您的数据的某种阈值日期。 如果解析日期早于此日期,则添加100年。 一种安全的方法是在输入字符串前加上适当的世纪。 在这个例子中,我选择1970作为截止值:
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还发布了一个使用DateTimeFormatInfo
的好例子,我暂时忘记了:)