Reputation: 5249
i am comparing 2 date fields to see if the first date field is less than the 2nd one but i am getting this error "String was not recognized as a valid DateTime" and it is failing at this line
DateTime Field2 = DateTime.Parse(gr.Cells[10].Text);
this is how this date field look like in my table: 2012-11-08
DateTime Field1 = DateTime.Parse(gr.Cells[3].Text);
DateTime Field2 = DateTime.Parse(gr.Cells[10].Text);
DateTime strDate = System.DateTime.Now;
if (Field2 == null && Field1 < strDate)
Upvotes: 2
Views: 3365
Reputation: 2450
According to the MSDN entry on DateTime.Parse:
The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture.
You are most probably getting the error because your current thread culture has a vastly different date format than that of the string you have provided.
What you can do is to specify the format that you will be using for the date:
DateTime.ParseExact(gr.Cells[10].Text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
Upvotes: 1
Reputation: 56222
Use DateTime.ParseExact
:
var res =
DateTime.ParseExact("2012-11-08", "yyyy-MM-dd",
CultureInfo.InvariantCulture);
Upvotes: 3