views:

77

answers:

2

A client is sending a string containing a date in format YYYYMMDDHHmmSS (e.g. 201004224432). There are no separators like / or -.

How can I easily convert this to a DateTime object? Convert.ToDateTime() does not work.

+8  A: 

Use DateTime.ParseExact:

var date = DateTime.ParseExact(
                       "201004224432", 
                       "yyyyMMddHHmmss",
                       CultureInfo.InvariantCulture);

Note the tweaks to your format string to work appropriately.

Reed Copsey
+1 for migrating the format string #mindreading
Michael Haren
@Michael: Thanks! Suggestions won't seem to work unless you fix all of their problems ;)
Reed Copsey
+8  A: 

You want DateTime.ParseExact, which can take in a formatting string like yours and use it to parse the input string.

Matt Greer