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? :)
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.
[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.
string x = dt. ToString("yyyy-MM-dd", CultureInfo. InvariantCulture);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With