Parsing this kind of string in DateTime is Friday, March 22nd, 2013 (C #)

I have a big piece of text:

.... advises that Friday, March 22nd, 2013 may be declared a day ...

I need to find and then analyze DateTime (Friday March 22, 2013). I can find it and use DateTime.TryParse to get almost everything, but the ordinal suffixes (st, nd, rd, th) throw me away.

When I create a format string before calling the TryParse method, are there any wildcards that I can use to account for these suffixes? Or any other suggestions?

Thank!

+5
source share
3 answers

What about replacing unwanted characters with regex?

regex : "(?<=\d)[a-z]{2}".

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));

:

22/03/2013 00:00:00

, .

+2

Brute Force.

. Fuji, .

string date = "Friday 22nd March 2013";
string[] split = date.Split(' ');
string dayOfWeek = split[0]; // throw away & don't need
int day = Convert.ToInt32(split[1].SubString(0, split[1].Length - 2);
int month = 0;
switch (split[2]) {
  case "January": month = 1; break;
  case "February": month = 2; break;
  case "March": month = 3; break;
  case "April": month = 4; break;
  case "May": month = 5; break;
  case "June": month = 6; break;
  case "July": month = 7; break;
  case "August": month = 8; break;
  case "September": month = 9; break;
  case "October": month = 10; break;
  case "November": month = 11; break;
  case "December": month = 12; break;
}
int year = Convert.ToInt32(split[3]);
var dateTime = new DateTime(year, month, day);
Console.WriteLine(dateTime);

100% " DateTime". IDE.

+1

There is an overload DateTime.Parsethat allows multiple format strings - you can pass ordinals in the form of literals, like this auxiliary method (which uses the flow locale to develop spelling for a month / day):

private static DateTime ParseOrdinalDateTime(string dt)
{
    string[] expectedFormats = new[] {
                                        "dddd d'st' MMMM yyyy",
                                        "dddd d'nd' MMMM yyyy",
                                        "dddd d'rd' MMMM yyyy",
                                        "dddd d'th' MMMM yyyy"
                                      };

    return DateTime.ParseExact(dt, expectedFormats, null, DateTimeStyles.None);
}
0
source

All Articles