0

I am trying to convert the following date string into datetime object. But for some reason it does not work. Any idea what the issue could be ?

string dt = "22-08-2018 16:53:00:000";
var date = Convert.ToDateTime(dt);
Console.WriteLine(date);

// Shaiz

Shaiz
  • 9
  • 2

2 Answers2

0

The input string seems wrong. With "22-08-2018 16:53:00.000" it will work. Note the use of "." to separate seconds and milliseconds

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
0

I think this may depend on the current culture. The value in your example appears to be day-month-year, and if attempting to convert in the "en-US" culture (for example), it will produce the System.FormatException: String was not recognized as a valid DateTime. If you know what the format of the datetime string will be, you can "force" it into the conversion. Here's a unit test using your example input string:

    [TestMethod]
    public void TestMethod2()
    {
        var dtFormat = new DateTimeFormatInfo();
        dtFormat.ShortDatePattern = "dd-MM-yyyy"; // force to day-month-year

        string dt = "22-08-2018 16:53:00.000";
        var date = Convert.ToDateTime(dt, dtFormat);

        Assert.AreEqual(new DateTime(2018, 08, 22, 16, 53, 0), date);
    }
Frank Alvaro
  • 468
  • 4
  • 12