-2

How do I convert this string into a date time with milliseconds

03/04/2019 15:16:57.73

The format is day/month/year hour:minutes:seconds.milliseconds.

I tried it like this:

var format = "dd/MM/yyyy HH:mm:ss.fff";

var year = dateTime.Substring(0, 4);
var month = dateTime.Substring(4, 2);
var day = dateTime.Substring(6,2);
var hour = dateTime.Substring(8, 2);
var minute = dateTime.Substring(10, 2);
var seconds = dateTime.Substring(12, 2);
var miiliseconds = dateTime.Substring(14, 2);
var stringDate = $@"{day}/{month}/{year} {hour}:{minute}:{seconds}.{miiliseconds}";
var transactioDateTime = DateTime.ParseExact(stringDate, format, CultureInfo.InvariantCulture);

But I get an error of

Additional information: String was not recognized as a valid DateTime.

How can I fix this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Ibanez1408
  • 4,550
  • 10
  • 59
  • 110

1 Answers1

4

Seems like you don't need substrings at all.

Just put your date string right into ParseExact and you will get what you want.

However the error there is because you have different milliseconds format: it expects you will put three digits there but you passed only two:

var dateTime = "03/04/2019 15:16:57.73";

var format = "dd/MM/yyyy HH:mm:ss.ff"; - this is the fix.

mjwills
  • 23,389
  • 6
  • 40
  • 63
mexanichp
  • 413
  • 3
  • 10
  • Thank you. This is exactly what was wrong. I';ll mark it as answer after 6 minutes. – Ibanez1408 Apr 04 '19 at 03:33
  • 1
    Just for clarity, parsing as `dd/MM/yyyy HH:mm:ss.ff` implies that the `.73` in the `dateTime` string is 730ms. Is that what the OP wants? – Enigmativity Apr 04 '19 at 03:37