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.
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.
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.
the easiest way to reach ONLY date is the simple function in Datetime: DateTime dt = DateTime. now; String BirthDate = dt. ToShortDateString();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With