Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

c# - DateTime string parsing

I have made a generic parser for parsing ascii files. When I want to parse dates, I use ParseExact function in DateTime object to parse, but I get problems with the year.

The text to parse is i.e. "090812" with the parseExact string "yyMMdd".

I'm hoping to get a DateTime object saying "12/8-2009", but I get "12/8-1909". I know, that I could make an ugly solution by parsing it afterwards, and thereby modifying the year..

Anyone know of a smart way to solve this ??

Thanks in advance..

S?ren

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...