Reputation: 610
How should I write the format of the dates I'm trying to parse when they are inconsistent?
DateTime.TryParse(date, out dateParsed);
sale.DateProcessed = dateParsed;
handle the error, specify a new format, and keep trying with different formats?
or is there a way to do it in one shot?
here is an extract of my data, which as you can see are not very consistent formatwise:
Nov. 09
Oct. 09
Sept 09
May 09
Mar. 09
Feb. 09
Jan. 09
Dec. 08
Nov. 08
Oct. 08
Sept. 08
August 08
July 08
June 08
May 08
April 08
March 08
Feb 08
Jan 08
Dec 07
Nov 07
Upvotes: 0
Views: 666
Reputation: 579
Use DateTime.TryParseExact with array of custom formats:
DateTime.TryParseExact(
dateString,
new String[]{
"MMM yy",
"MMM. yy",
"MMM\\t. yy",// for 4-letters Sept.
"MMMM yy"}, // full name of month
New CultureInfo("en-US"),
DateTimeStyles.None,
dateValue
);
Upvotes: 3
Reputation: 32179
Here you go:
DateTime GetDate(string raw){
int month;
switch(raw.Substring(0,3).ToLower()){
case "jan": month = 1; break;
case "feb": month = 2; break;
...
case "dec": month = 12; break;
default: throw new ArgumentException("raw", "Failed to parse month");
}
int year = int.Parse("20" + raw.Substring(raw.Length - 2));
return new DateTime(year, month, 1);
}
Upvotes: 0
Reputation: 1685
Upvotes: 0
Reputation: 8424
Just do this:
date = date.Substring(0, 3) + " 20" + date.Substring(date.IndexOf(' ') + 1);
Upvotes: 1
Reputation: 119
I would just have a Dictionary with mapping for short month names to full month names Jan => January. And then before parsing convert short name to the long name.
Upvotes: 0
Reputation: 62027
If that is representative of your data, could you just massage each one and:
1) chop the month to the three letter abbreviation (string.Substring should do the trick)
2) append "20" to the front of the year
and then parse from there? Or are there even more formats to deal with? All in all your data is actually pretty consistent.
Upvotes: 1