Wednesday, September 15, 2010


Recently, I had to work out the number of months between two arbitrary dates. In C# this is a bit of a challenge, simply because DateTime.Subtract(DateTime) returns a TimeSpan, which does not have a Months property.

This is because TimeSpan doesn't know which months it would be referring to. Specifically, to know how many months there are in a date range you need to count each month index from date A to date B. Problem being, if you don't know those arbitrary dates - you only have a count of days - how many months does that range cover?

Example: How many months does 30 days represent? Answer: 1.


Why?... Because if we are talking about February, it's two months. If we're talking about August it's not a whole month.

The solution is to take into account the specific dates being used in the subtraction and count their months, unfortunately. Yeah, I don't want to write that code either.

However, for the C#'ers among us, there is a solution. VB has a DateDiff class which can do this for you. Just use the Microsoft.VisualBasic namespace and the static DateDiff method, as I found out here:
Here's a post about writing your own:

No comments:

Post a Comment