Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing this kind of string into DateTime - "Friday 22nd March 2013" (C#)

I've got a large chunk of text like this:

....advises that Friday 22nd March 2013 has the potential to be declared a day.....

I have to locate and then parse DateTime in it (Friday 22nd March 2013). I can locate it and use DateTime.TryParse to get almost everything, but the ordinal suffixes (st,nd,rd,th) are throwing me off.

When I'm constructing the format string before calling the TryParse method are there any wildcard characters I can use to take into account those suffixes? Or any other suggestions?

Thanks!

like image 292
Sundance Avatar asked Oct 21 '22 14:10

Sundance


1 Answers

How about replacing the unwanted characters using a regex?

As an example the following regex should do the job: "(?<=\d)[a-z]{2}".

Example code

string date = "Friday 22nd March 2013";
var r = new Regex(@"(?<=\d)[a-z]{2}");
String result = r.Replace(date, "");
Console.WriteLine(DateTime.Parse(result, CultureInfo.InvariantCulture));

Output:

22/03/2013 00:00:00

This should take care of most cases, but make sure to test it properly.

like image 148
eandersson Avatar answered Oct 27 '22 00:10

eandersson