My system short date time form开发者_如何学Goat is d/M/yyyy. I'm passing "03/29/2011 02:38:18 PM", so it is giving error "String was not recognized as a valid DateTime"
DateTime.Parse("03/29/2011 02:38:18 PM")
If date time format of machine is set to m/d/yyyy, it works perfectly.
Edit: My application is a winform application, it contains a data gridview, this grid view contains a custom DateTime control (columns), which is created by other developer. This error is occurring when I try to change value of this datetime column in grid. VS debugger is not catching the exception, so I'm not able to find location where I should try fixing it.
Thanks
According to the format d/M/yyyy
, 03/29/2011
would amount to month number 29 that does obviously not exist.
The other format has day and month switched, and the string then represents 29. March which is a perfectly valid date.
From MSDN:
Important Because the Parse(String) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results. If a specific date and time format will be parsed across different locales, use the DateTime.Parse(String, IFormatProvider) method or one of the overloads of the ParseExact method and provide a format specifier.
Yes, well, the DateTime.Parse function uses the system format to parse the date, unless you provide a FormatProvider. Obviously in case of d/m/yyyy there is no month 29 so the parsing fails
Use DateTime.ParseExact() instead. You can specify exactly how to parse the date if you know what the string looks like going into the function by passing in the correct FormatString. If the standard DateTime Format Strings don't work, you can use a custom DateTime Format String.
Use DateTime.ParseExact
to parse datetime from string
Example:
DateTime.ParseExact("2001-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
You could try to change the culture information, so your input matches the format of the system.
So try to add this in the web.config:
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-US" />
You can find the answer here: String was not recognized as a valid DateTime " format dd/MM/yyyy"
You can parse the Date with a corresponding CultureInfo, which defines the date format and the order of the date parts (Month,Day,Year) or (Day,Month,Year).
Or you could use the ParseExact and give it a format string as described in the answer above.
See "convert Different formate of DateTime to specific String format in c#"
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}
精彩评论