ebcrypto
ebcrypto

Reputation: 610

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

Upvotes: 0

Views: 666

Answers (6)

chapluck
chapluck

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

grenade
grenade

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

Virtually Real
Virtually Real

Reputation: 1685

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

Upvotes: 0

Cokegod
Cokegod

Reputation: 8424

Just do this:

date = date.Substring(0, 3) + " 20" + date.Substring(date.IndexOf(' ') + 1);

Upvotes: 1

victor
victor

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

Matt Greer
Matt Greer

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

Related Questions