Parsing a string to datetime in .netcore from format dd.MM.yyyy hh:mm:ss

Viewed 275

I found similar questions, but none is covered this case.

Im trying to do follows:

string dateTime = "28.11.2020 16:08:43"

var date = DateTime.ParseExact(dateTime, "dd.MM.yyyy hh:mm:ss", CultureInfo.InvariantCulture)

but Im getting exception:

System.FormatException: String '28.11.2020 16:08:43' was not recognized as a valid DateTime.
   at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
1 Answers

You're using hh in your format string, which means "hour of halfday, in the range 1-12". You want HH, which means "hour of day, in the range 0-23". The actual value (16) isn't in the range 1-12, hence the error.

Any time you run into date/time formatting or parsing issues, it's worth checking your date/time format very, very carefully against the documentation.

Related