Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.ParseExact gives String was not recognized as a valid DateTime.

Tags:

I'm trying to parse a date string into a DateTime variable. I've found out that ParseExact is the way to do it, but I try this I get the error:

String was not recognized as a valid DateTime.

string timeFormat = "dd-MM-yyyy hh:mm:ss"; DateTime startDate = DateTime.ParseExact(reader["startdate"].ToString(), timeFormat, CultureInfo.InvariantCulture); DateTime nextDate = DateTime.ParseExact(reader["nextdate"].ToString(), timeFormat, null); 

I've tried both with null (which happens to work on another page), and the CultureInfo.InvariantCulture.

reader["startdate"].ToString() output: 01-08-2012 15:39:09

and

reader["nextdate"].ToString() output: 01-08-2012 15:39:09

I think it should work, but it doesn't.

Somebody have an idea what is wrong? :)

like image 446
DesignMonkeyDK Avatar asked Aug 01 '12 19:08

DesignMonkeyDK


People also ask

How to use DateTime ParseExact in c#?

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

How do I fix string is not recognized as a valid DateTime in VB net?

[FormatException: String was not recognized as a valid DateTime.] then it is telling you that whatever is in the text box cannot be recognised as a date. You need to either change the textbox contents so it is a valid date, or provide a custom date format for the date parser that matches the text box contents, or both.

How do I change the date format in C sharp?

string x = dt. ToString("yyyy-MM-dd", CultureInfo. InvariantCulture);


1 Answers

You're using hh in your format string. That's a 12-hour "hour of day" field. The value 15 isn't in range...

You want HH instead, which is the 24-hour specifier.

See the MSDN custom date and time format strings documentation for more information.

like image 155
Jon Skeet Avatar answered Oct 10 '22 02:10

Jon Skeet