Sunday, April 27, 2008

Use DateSerial Function To Avoid Regional Settings Problem In VB.NET

This is based on my experience. I used to construct a date type with from string. The sample code is as follow:


Dim dt As Date = CDate("2/3/2008")
MessageBox.Show(dt.ToLongDateString)

Hell yeah! I realized now that this is not a good way. When you execute the code above by using Regional Options set to English US - which Short date format in this setting is "mm/dd/yyyy" - you'll get a message box with message "Sunday, February 03, 2008". Comparing the result with Regional Options set to English (Australia) - which the format is "dd/mm/yyyy" - we'll get a message box with message "Sunday, 2 March 2008". Whew! So which date do the code means?

Oh, I means February 03, 2008! It's just a date, we can fix it just by changing it, it's not a big deal! Hell yeah! You can just simply change it when we are talking about one or two variable, and a simple program like those "Hello World Style" like above. When we're talking about an enterprise application like e-banking which all reports are based on transaction date, believe me that this style of code will bring you to hell.

The simple way to avoid this Regional Options problem, is just get yourself used to construct the datetime variable value by define its day, month, and year value specifically. In .NET you can use DateSerial function.

According to msdn this function returns a Date value representing a specified year, month, and day, with the time information set to midnight (00:00:00). The format of this function is as follow:


Public Function DateSerial( _
ByVal [Year] As Integer, _
ByVal [Month] As Integer, _
ByVal [Day] As Integer _
) As DateTime

So, when you means February 03, 2008, the code above will be as follow:


Dim dt As Date = DateSerial(2008, 2, 3)
MessageBox.Show(dt.ToLongDateString)

The code above will give you February 03, 2008 in any Regional Options you use!

This is a very simple thing to do, but not all realized it's effectiveness (including me, was). But, just by using this kind of simple code behavior will avoid you from a lot of problem caused by Regional Options different from miscalculating reports to unpredictable error in your application.

No comments: