Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 738
David Glenn Avatar asked Jan 13 '10 17:01

David Glenn


People also ask

How do you parse a string to a date?

parse() The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.

Does C# have a date type?

To set dates in C#, use DateTime class. The DateTime value is between 12:00:00 midnight, January 1, 0001 to 11:59:59 P.M., December 31, 9999 A.D.

How can I get only the date from DateTime format?

the easiest way to reach ONLY date is the simple function in Datetime: DateTime dt = DateTime. now; String BirthDate = dt. ToShortDateString();


2 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); 
like image 177
Rubens Farias Avatar answered Sep 30 '22 09:09

Rubens Farias


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); 
like image 20
kenny Avatar answered Sep 30 '22 11:09

kenny