SharonsFuzzyArian











{April 9, 2010}   Convert.ToDateTime

We found a weird working of the DateTime feature in the Visual Studio 3.5 Framework. The scenario was to have a DateTime variable and to validate it against the business logic.

This is how we had set the DateTime feature:

DateTime ldtDate = Convert.ToDateTime(“1/1/” + lintYear.ToString())

where lintYear is any Interger.

When the lintYear is any 4 digit, then this is converted properly, but the trouble comes, when u need to pass it as a single or double digit number.

If we pass 2003, then the date will be ’1/1/2003′. But what happens, when you pass it a year in the 1st few centuries.

Say if we pass it as 1, i.e. 1st Century  or 2nd century

DateTime ldtDate = Convert.ToDateTime(“1/1/” +1.ToString())

This will be considered as ’1/1/2001′, strangely!!

Similarly, if we pass 3, 4 or 5, then it will be ’1/1/2003′, 1/1/2004′, ’1/1/2005′ accordingly..

Unless we pass the Year value as ’0001′ or even ’001′, then only it takes it as ’1/1/0001′.

Even if we pass it as ’1′ or ’01′, then it will again be ’1/1/2001′.

So be double careful when you are operating on the DateTime paramter. ;)

This is one crazy scenario, and the best way to avoid all these mishaps is to always use this feature,

DateTime ldtDate = new DateTime(Year, Month, Day);

Here in whatever format the Year is passed, then it takes it correctly in the prescribed way.

I have made sure, that I use this as the maximum way to avoid all future confusions by the Convert feature.

So stay aware and awake!! ;)



et cetera
Follow

Get every new post delivered to your Inbox.