Parsing a Date Like "Wednesday 13th January 2010" with .NET

Viewed 2598

How can I convert the following strings to a System.DateTime object?

Wednesday 13th January 2010
Thursday 21st January 2010
Wednesday 3rd February 2010

Normally something like the following would do it

DateTime dt;
DateTime.TryParseExact(value, "dddd d MMMM yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);

but this doesn't work because of the 'th', 'st' or 'rd' in the string

Update

It appears that DateTime doesn't support formatting the 'th', 'st', 'rd' etc so they need to be stripped before parsing. Rubens Farias provides a nice regular expression below.

7 Answers

What about strip them?

string value = "Wednesday 13th January 2010";
DateTime dt;
DateTime.TryParseExact(
    Regex.Replace(value, @"(\w+ \d+)\w+ (\w+ \d+)", "$1 $2"),
    "dddd d MMMM yyyy", 
    DateTimeFormatInfo.InvariantInfo, 
    DateTimeStyles.None, out dt);

Another approach.

string sDate = "Wednesday 13th January 2010";
string[] sFields = sDate.Split (' ');
string day = sFields[1].Substring (0, (sFields[1].Length - 2));
DateTime date = new DateTime (sFields[3], sFields[2], day);

Where does "th", "st","nd" or "rd" appear below?

  • monday
  • tuesday
  • wednesday
  • thursday
  • friday
  • saturday
  • sunday

  • january

  • february
  • march
  • april
  • may
  • june
  • july
  • august
  • september
  • october
  • november
  • december

However you know those 4 will always be followed by a space. So unless I've missed something, a simple

value = value.Replace("August","Augus").Replace("nd ","").Replace("st ","").Replace("nd ","").Replace("rd ","").Replace("Augus","August");
DateTime dt;
DateTime.TryParseExact(value,"DDDD dd MMMM yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);

I remembered this post on using MGrammar to parse a lot of different ways to express dates and times. It doesn't exactly answer your question, but it might serve as a useful base depending on what your ultimate goal is.

Related