Convert string to DateTime in c#

What is the easiest way to convert the following date created using

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

into a proper DateTime object?

20090530123001

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


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);

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

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

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