Search code examples
c#stringdatetimestring-conversion

Converting this string format to a valid DateTime?


The string in question: "2003:12:14 12:01:44" (yyyy:MM:dd hh:mm:ss)

How would I be able to convert this to a valid datetime in C#? I tried Convert.ToDateTime(str), but to no avail.


Solution

  • Use the right DateTime format and supply DateTime.ParseExact with that format. Note that since your time doesn't show AM or PM, it may be safer to assume that it uses 24-Hr format (use capital HH) than 12-Hr AM PM (not hh) format. The following code should work:

    string format = "yyyy:MM:dd HH:mm:ss"; //note: use HH not hh
    var result = DateTime.ParseExact("2003:12:14 12:01:44", format, CultureInfo.InvariantCulture);
    

    Check more on the available DateTime formats here (standard) and here (custom).