views:

393

answers:

3

Hi, can someone please tell me the easiest way to convert the following date created using..

dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture)

into a proper DateTime object?

20090530123001

thanks.

NB: I have tried Convert.ToDateTime(...) but got a FormatException.

+4  A: 

Try this:

DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

If the string may not be in the correct format (and you wish to avoid an exception) you can use the DateTime.TryParseExact method like this:

DateTime dateTime;
DateTime.TryParseExact(str, "yyyyMMddHHmmss",
    CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
Andrew Hare
Woops, +1 to you.
Kyle Rozendo
+1  A: 

http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

var date = DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)
eglasius
+1  A: 

Good tutorial here -- I think you just want Parse, or ParseExact with the right format string!

Alex Martelli