Saturday, December 12, 2009

Weekly Source Code: C# DateTime Developer Pitfall

Base upon my previous blog post that every language has some pitfalls I had a production issue and saw one of the pitfalls that C# have with the DateTime class which is part of the .Net framework.

I renamed this title since its more a pitfall of the developer not understanding the proper use of the DateTime class. The all point is that your telling the constructor to create a date, you don't tell it to work with increments.

In the next code you want to get the 1ste date of the following month:

DateTime currentDate = new DateTime(2009, 11, 05);
DateTime nextDate = new DateTime(currentDate.Year, currentDate.AddMonths(1).Month, 1);
Console.WriteLine("nextDate: " + nextDate.ToString("dd/MM/yyyy"));

So the answer is 01/12/2009 which is correct but what if you do the following:

DateTime currentDate = new DateTime(2009, 12, 05);
DateTime nextDate = new DateTime(currentDate.Year, currentDate.AddMonths(1).Month, 1);
Console.WriteLine("nextDate: " + nextDate.ToString("dd/MM/yyyy"));

Code is exactly the same, I just change the month to December since you want to get the day for the 1ste of Jan 2010 but the end result is: 01/01/2009. Ouch!!

Yes the DateTime object doesn't increment the year (2009 -> 2010).

To fix:

DateTime currentDate = new DateTime(2009, 12, 05);
DateTime nextDate = new DateTime(currentDate.Year, currentDate.Month, 1);
nextDate = nextDate.AddMonths(1);
Console.WriteLine("nextDate: " + nextDate.ToString("dd/MM/yyyy"));

You see that you can't increment in a DateTime.

2 comments:

Owe Jørgensen said...

Excellent article covering the pitfall of datetime arithmetrics.

However, if I were to try adding 1 month to Dec 5th, 2009, Iæd do it via the DateTime.Add(TimeSpan) overload, such as:

DateTime date = new DateTime(2009, 12, 5);
TimeSpan span = new TimeSpan { Months = 1 }; // Thank god for initializers
DateTime future = date.Add(span);

This will result in the correct increment of the year. I always use TimeSpan to add to DateTime objects since I just don't want to bother with the finer arithmetrics of calendar manipulation. The TimeSpan method also covers any specific locale calendar quirks too.

Rahul said...

First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I was with the

information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful for community.

There is a good C# resource site, Have alook

http://CSharpTalk.com

Thanks again
Rahul