C# – Converting a String to DateTime

cdatetime

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

Best Answer

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