Hi, Does anyone know of an easy(built in) way to convert a string like '20081231T130000' (ICalendar I think) to DateTime in C#? Or do I need to parse the string?
+5
A:
Try this:
DateTime when = DateTime.ParseExact("20081231T130000",
"yyyyMMddTHHmmss",CultureInfo.InvariantCulture);
Aside: it is close to the format used in xml, but not quite close enough - otherwise XmlConvert
wraps this:
DateTime when = XmlConvert.ToDateTime("2008-12-31T13:00:00");
Marc Gravell
2009-02-03 10:06:18
Once again thanks Marc.
2009-02-03 10:19:53
+2
A:
This seemed to work:
string dateTimeString = "20080115T115959";
string format = "yyyyMMddTHHmmss";
IFormatProvider us = new System.Globalization.CultureInfo("en-US", true);
DateTime dt = DateTime.ParseExact(dateTimeString, format, us);
Andy White
2009-02-03 10:12:42
Needs to be HH (0-23), not hh (0-11) - and invariant would probably do just fine since there is no culture-specific info in the string.
Marc Gravell
2009-02-03 10:14:49
Thanks for catching that... I guess that's why I'm only at 11 reputation :)
Andy White
2009-02-03 10:33:16
Virtual +1 for the HH comments to Jon and Marc. I've just spent an hour thinking "that worked this morning" ... :)
Unsliced
2009-11-09 17:02:57