-1

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

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Rose
  • 613
  • 4
  • 22

2 Answers2

3

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);

The exception is / is actually a special placeholder for the date separator defined in the current culture. Here we're using the invariant culture, so this could work if and only if - is also set as the date separator for that culture (hint: it's not).

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

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);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
CodeWhore
  • 951
  • 6
  • 9