I have a string containing the date and time
string startDate = "30-09-2022 09:00:00";
DateTime startdate = DateTime.ParseExact(startDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
I want to convert to DateTime, but it doesn't work and the error message is System.FormatException: String '30-09-2022 09:00:00' was not recognized as a valid DateTime
How to solve it?
Note: the string is in 24-hour format
CodePudding user response:
The "Exact" in ParseExact()
means it... your format string much match the data perfectly. For example, you can't use /
if the data has -
.
DateTime startdate = DateTime.ParseExact(startDate, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
CodePudding user response:
Your date string has '-' between the date elements and your format string has '/' slashes. This is not an exact parse.
string startDate = "30-09-2022 09:00:00"; DateTime startdate = DateTime.ParseExact(startDate, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
OR
string startDate = "30/09/2022 09:00:00"; DateTime startdate = DateTime.ParseExact(startDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);