tags:

views:

337

answers:

3

Hi,

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

+2  A: 

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 :)

Thorarin
+1  A: 

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

CodeByMoonlight
+10  A: 

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

Jon Skeet
I kinda like your theoretical solution. The `DateTimeFormatInfo` is only a one time setup anyway. It also allows for different cutoffs rather than just assuming everything is in this century.
Thorarin
Looks nice..Not quite sure, what you are trying to do..!?But anyways, dtfi.Calendar.TwoDigitYearMax can only be set to a number above 99.. :-(..And I'm not to happy about the solution with just adding "20" in front, since I cant garantee this not beeing used to look at older data < year 2000..
MüllerDK
@MullerDK: Sorry, it should be set to 2000... or maybe 1910 if you want 100812 to be 1910 etc.
Jon Skeet
(Edited the code for 1910.) What's the earliest year you will see? At some point, you'll end up with an ambiguous format... you can't represent a range of more than 100 years with just two decimal digits. Note that if you set it to 1910, then next year you'll need to set it to 1911 etc. You might want to use `DateTime.Now.Year - 100`.
Jon Skeet
FYI DateTimeFormatInfo.Clone() does call this.Calendar.Clone()
daveidmx