How can I convert the following strings to a System.DateTime object?
Wednesday 13th January 2010
Thursday 21st January 2010
Wednesday 3rd February 2010
No credit to me but this looks interesting for general DataTime parsing: http://www.codeproject.com/KB/datetime/date_time_parser_cs.aspx?msg=3299749
What about strip them?
string value = "Wednesday 13th January 2010";
DateTime dt;
DateTime.TryParseExact(
Regex.Replace(value, @"(\w+ \d+)\w+ (\w+ \d+)", "$1 $2"),
"ffffdd d MMMM yyyy",
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None, out dt);
Where does "th", "st","nd" or "rd" appear below?
sunday
january
However you know those 4 will always be followed by a space. So unless I've missed something, a simple
value = value.Replace("August","Augus").Replace("nd ","").Replace("st ","").Replace("nd ","").Replace("rd ","").Replace("Augus","August");
DateTime dt;
DateTime.TryParseExact(value,"DDDD dd MMMM yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);
Another alternative using escape characters for handling (st
, nd
, rd
, and th
) without stripping them before the call of DateTime.TryParseExact
string dtstr = "Saturday 23rd January 2016";
DateTime dt;
string[] formats = new string[] {
"ffffdd d\\s\\t MMMM yyyy", "ffffdd d\\n\\d MMMM yyyy",
"ffffdd d\\r\\d MMMM yyyy", "ffffdd d\\t\\h MMMM yyyy" };
bool result = DateTime.TryParseExact(dtstr, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Expanding on Kenny's approach, I added some code to pass integers to the DateTime variable...
string sDate = "Wednesday 13th January 2010";
string[] dateSplit = sDate.Split (' ');
string day = dateSplit[1].Substring(0, dateSplit[1].Length - 2);
int monthInDigit = DateTime.ParseExact(dateSplit[3], "MMMM", CultureInfo.InvariantCulture).Month;
DateTime date = new DateTime(Convert.ToInt16(year), monthInDigit, day);
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);