Link to home
Start Free TrialLog in
Avatar of NewtonianB
NewtonianB

asked on

how to parse exact day"th"

How can I parse exact this string in c#?

It seems it works with DateTime.Parse() as long as the "th" is not there how can I fix this?

Friday 18th February 2011 8:11:04 AM
ASKER CERTIFIED SOLUTION
Avatar of Ramone_Hamilton
Ramone_Hamilton
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That's a really good catch!  I myself detest regular expressions as they always beat me down.  I know this may be excessive, but what about taking your string, split it by the spaces and then do the replace?

Here is a revised version.

            string date = "Friday 18th February 2011 8:11:04 AM";

            string[] dates = date.Split(' ');

            dates[1] = dates[1].Replace("th", string.Empty);
            dates[1] = dates[1].Replace("rd", string.Empty);
            dates[1] = dates[1].Replace("st", string.Empty);

            StringBuilder newDate = new StringBuilder();

            newDate.Append(dates[0]).Append(" ").Append(dates[1]).Append(" ").Append(dates[2]).Append(" ").Append(
                dates[3]).Append(" ").Append(dates[4]).Append(" ").
                Append(dates[5]);

            DateTime.Parse(newDate.ToString()); 

Open in new window

OK, I agree - again good idea, I'd go with splitting and replacing dates[1].

However to use StringBuilder to re-assemble the string is an overkill, I think.

I'd write it as :

string cleaneddateStr = dates[0] + " " + dates[1] + " " + dates[2] + " " + dates[3] + " " + dates[4] + " " + dates[5]

Compiler is clever enough to create just a one string here so - no much overhead. With StringBuilder - quite a lot of overhead. I tested this couple of years ago.

Anyway, it works
Avatar of NewtonianB
NewtonianB

ASKER

we forgot "nd" also