-1

How to convert string MM/dd/yyyy HH:ss to DateTime without changing the format. I just need to change the datatype from string to DateTime that's it. I have tried various ways but it doesn't give me my expected output.

String Input : 01/28/2018 20:00
Expected DateTime output : 01/28/2018 20:00 (only datatype should change)

Below are the some methods that I have tried:

  1. DateTime.ParseExact("01/28/2018 20:00","MM/dd/yyyy HH:ss", CultureInfo.InvariantCulture): gives me 2018-01-28T20:00:00
  2. Convert.DateTime("01/28/2018 20:00") gives me "String was not recognized as a valid DateTime" exception
  3. DateTime.Parse("01/28/2018 20:00") this also gives me the same exception

Any help much appreciated.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
GOPI KRISHNAN
  • 36
  • 1
  • 6
  • 6
    `DateTime` do not have a format. What makes you think they do? – mjwills Mar 28 '18 at 11:23
  • 3
    If it helps, think of it like integers - there's no difference between `int x = 16;` and `int y = 0x10;`. They store the same value. There's no format retained. `DateTime` is the same - it's just a date and time (and kind, but that's somewhat different). – Jon Skeet Mar 28 '18 at 11:26
  • This might be helpful: https://stackoverflow.com/questions/919244/converting-a-string-to-datetime – Prasad Telkikar Mar 28 '18 at 11:30

1 Answers1

0

As it was told in comments above, DateTime itself has no formatting, it happens only for string representation of the date and time. So, the best thing you can do here is to store two values: DateTime value itself and expected string format. Then, once converting your date & time into printable thing you just have to specify that stored format.

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42