This blog is subject the DISCLAIMER below.

Friday, August 17, 2007

Another Solution to DateTime problems (.Net)

Now that I read th last post, I remembered another solution that can be implemented on the Application level rather than the implementing it in your SQL statements,

Of course we have three parts of the problem. The first is how to display dates without any problems; like misinterpretation (dates like 2/3/2007 & 3/2/2007, if you don't know how your DB interpret dates) or throwing exceptions. The second is how to read user-input dates. The third is how to write dates to the DB in the right form & again without misinterpretation.

Displaying dates in the right form:


Remember that the problem is not just about the user misinterpret the displayed date, it's also your problem when you come to next part. for eg when displaying dates for the user to edit.

In this part we have to display the date with an enforced format that's:

string myDateFormat = ConfigurationManager.AppSettings["myDateFormat"];
Date.ToString(myDateFormat);

This way we can enforce the date format we want & also it's just a matter of configuration (just edit the configuration file to change the format of dates across a whole solution without rebuilding).

Reading user-input dates:


Now we come to last part, which much related to the previous part. Now after displaying the dates properly to the users, we need to make sure that the input of the user through editing the displayed ones or just typing new ones won't be misinterpreted. the solution itself comes in two parts:

  1. First, the input field must be validated according to the same format we are using through the solution, better be by retrieving the format string from the configuration file as we did in the previous part (for the same reasons; allowing all-in-one configuration).
  2. Given that that enforced a When parsing the date, use "ParseExact" not "Parse" to parse your date.

DateTime myTime = DateTime.ParseExact(myStringTime, myDateFormat, null);

Writing dates to your DB:


Now that we have the properly parsed date we should format in like the format below while writing to the DB

"yyyy-MM-dd"

Enforce the above format when writing dates to DB. The format is the standard format that won't be misinterpreted by the DB.

Conclusion:


Don't use Date.Pasre(...), unparameterized Date.ToString(), always use Date.ParseExact(...), & parametrized Date.ToString(). This way our application won't be affected by the date format of the machine it's running on or that of the DB server it's communicating with (either on the same machine or not).

No comments: