ASP.NET DateTime.Parse Error : String was not recognized as a valid DateTime
During the test period of an ASP.NET Web application, our test team had the following ASP.NET DateTime.Parse error.
System.FormatException: String was not recognized as a valid DateTime.
Any ASP.NET developer can realize easily what might cause this FormatException as the input string is not recognized as a valid DateTime value.
The error source is directly pointing to the code source of the error.
Dim nowDate As DateTime = DateTime.Parse(e.Row.Cells(columnIndex_NowDate).Text.Trim)
Actually the datetime string that is causing the format exception during DateTime.Parse() method call is : "7/13/2009 1:29:37 PM"
And to correctly handle this exception we should supply the System.IFormatProvider parameter as an additional parameter to the DateTime.Parse() funtion.
The System.IFormatProvider is an object that supplies culture specific format information.
Since the database I read data is in US English language in default, the System.IFormatProvider parameter should be configured for "en-US" culture info.
Below is the ASP.NET code in VB.NET for the solution.
nowDate = DateTime.Parse(inputDateString, System.Globalization.CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat)
