Converting a String to DateTime

dban picture dban · May 28, 2009 · Viewed 1.4M times · Source

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?

Answer

Christian C. Salvadó picture Christian C. Salvadó · May 28, 2009

Since you are handling 24-hour based time and you have a comma separating the seconds fraction, I recommend that you specify a custom format:

DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture);