-1

I've been trying to convert a string to DateTime but an error occurred. This is the code that gave the error:

public static string recorded = "12/07/2019 02:37:00 PM";
DateTime check = DateTime.ParseExact(recorded, "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);

As far as I'm concerned, the format I'm using matches the string perfectly (every number has 2 digits/letters, they have the same symbols used). I thought that maybe I was just using the wrong format so I tried using 2 formats from here.Specifically, "MM/dd/yyyy HH:mm tt" and "MM/dd/yyyy HH:mm:ss". Only the latter worked so I'm thinking that the problem lies in the AM/PM but the problem is that I need it, so I can't use the latter format. I even tried using lowercase pm and Pm but both didn't work.

  • https://stackoverflow.com/questions/2596969/why-can-t-datetime-parseexact-parse-the-am-pm-in-4-4-2010-42000-pm-using use `MM/dd/yyyy hh:mm:ss tt` – Luuk Nov 10 '19 at 15:35

2 Answers2

2

The format string HH refers to 24-hour format and cannot be used in conjunction with tt. Use hh instead. This:

DateTime check = DateTime.ParseExact(recorded, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

works just fine.

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
1

You need lower case hh: MM/dd/yyyy hh:mm:ss tt.

Stevo
  • 1,424
  • 11
  • 20