Parsing a Date Like "Wednesday 13th January 2010" with .NET
How can I convert the following strings to a System.DateTime object?
Wednesday 13th January 2010
Thursday 21st January 2010 Wednesday 3rd February 2010Normally 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.
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);
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[] {
"dddd d\\s\\t MMMM yyyy", "dddd d\\n\\d MMMM yyyy",
"dddd d\\r\\d MMMM yyyy", "dddd d\\t\\h MMMM yyyy" };
bool result = DateTime.TryParseExact(dtstr, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Where does "th", "st","nd" or "rd" appear below?
- monday
- tuesday
- wednesday
- thursday
- friday
- saturday
sunday
january
- february
- march
- april
- may
- june
- july
- august
- september
- october
- november
- december
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);
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
I remembered this post on using MGrammar to parse a lot of different ways to express dates and times. It doesn't exactly answer your question, but it might serve as a useful base depending on what your ultimate goal is.
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);
精彩评论