Parse Date with inconsistent formats
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
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
);
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.
Just do this:
date = date.Substring(0, 3) + " 20" + date.Substring(date.IndexOf(' ') + 1);
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.
- Tokenize each line using space as the separator
- First three letters give you the month in all cases
- Convert the second token to integer and add 2000 to it, to get the year.
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);
}
精彩评论