tags:

views:

98

answers:

3

I have a string like this:

"20090212"

and I want to convert to valid C# datetime.

Do I need to parse it out because that seems too much work?

+4  A: 

Have a look at the DateTime.TryParseExact method (MSDN). I prefer TryParseExact method to the ParseExact method because it returns a boolean telling you whether or not the conversion was successful instead of throwing an exception but either one will work.

TLiebe
+12  A: 

You can use DateTime.ParseExact:

DateTime result =
    DateTime.ParseExact("20090212", "yyyyMMdd", CultureInfo.InvariantCulture);
dtb
Thanks for the answer! It worked smoothly :)
john doe
nice tip, will definitely come in handy sometime
mattythomas2000
+2  A: 
DateTime.ParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture);

... and I really doubt I got there first.

Although for completeness, I prefer TryParseExact

DateTime dt;
if(DateTime.TryParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt)) { 
  // ... use the variable dt 
} 
Unsliced
In general, it is safer to use `CultureInfo.InvariantCulture` when you know that all input strings will be in a specific format. Sometimes format codes are interpreted differently when in different locales.
Brian