SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
ASP.NET, VB.NET, Microsoft .NET Framework, Microsoft Visual Studio, Windows Forms, Controls and more Tutorials and Articles for Programmers


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.
Code

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.

datetime parse not a valid datetime

Dim nowDate As DateTime = DateTime.Parse(e.Row.Cells(columnIndex_NowDate).Text.Trim)
Code




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)
Code


Visual Studio


Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.