Aug 30, 2010

String to DateTime, FormatException and ASP.NET

There are lots of bugs/errors due to improper handling of datetime. Sometime we don’t know the production server regional settings or the culture information. It may different from the development area. Thus this yields the errors on deployment if not handled properly. See one example:

If development server has en-US culture and the entire code is developed on this. See following code:

string str = DateTime.Now.ToString("MM/dd/yyyy");

DateTime dt = Convert.ToDateTime(str);

It is working fine in the development environment because en-US is "MM/dd/yyyy" format.

But If production server has en-CA culture then this will throw System.FormatException.

Error: An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: String was not recognized as a valid DateTime.

For production server the code should be following:

string str = DateTime.Now.ToString("dd/MM/yyyy");DateTime dt = Convert.ToDateTime(str);

But this will throw exception on the development environment.

So what should be proper steps?

1. Define proper culture information for the whole app:

In web.config define culture information


<configuration>
<system.web>
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-US"
/>

Now our app is independent of server culture settings. It will be treated as “en-US”.

2. If you need to pass datetime in the database(as a parameter of stored proc) as a string then pass "yyyy-MM-dd" format.

3. you can define format for a particular date:

System.Globalization.DateTimeFormatInfo MyDateTimeFormatInfo = new System.Globalization.DateTimeFormatInfo();

MyDateTimeFormatInfo.ShortDatePattern = "M/d/yyyy";

string StartDate = DateTime.Parse(dt.ToString("MM/dd/yyyy",MyDateTimeFormatInfo);

OR

DateTime.Parse("2/10/2006", new CultureInfo("en-US"));

4. Change culture setting of the server: It is for the knowledge purpose.

In Control Panel->”Regional and language settings”->Advance tab -> Tick the check box which says "Default User Account Settings"

Reboot your server.

The culture selected in the regional and language settings should now be picked up by your ASP.Net application if any culture is not specified in the app.

Enjoy this.