Originally published on my old Charteris blog

I recently had to calculate the span of time between two dates. The .NET structure TimeSpan was not good enough because I wanted to expose the span as Years, Months, Weeks and Days. I was sure that somebody would have been asked to solve this problem before so I turned to my favourite search engine.

Many of the early hits suggested the VisualBasic .Net function DateDiff. Whilst many people baulked at the idea of using a VB function in a C# app I would have been happy if it did the job. I imported the Microsoft.VisualBasic namespace and gave it whirl. The docs for DateDiff show an interval property described as the “String expression that is the interval you want to use to calculate the differences between date1 and date2”. Month and Year were an option so I tried them out with some test data. All looked good until I tried

            DateTime first = new DateTime(2006, 12, 31);

 

            DateTime second = new DateTime(2007, 01, 01);

 

            long diff = Microsoft.VisualBasic.DateAndTime.DateDiff(

                                                            Microsoft.VisualBasic.DateInterval.Year,

                                                            first,

                                                            second,

                                                            Microsoft.VisualBasic.FirstDayOfWeek.Monday,

                                                            Microsoft.VisualBasic.FirstWeekOfYear.Jan1);

This gave a diff for the Year of 1! Clearly the length of time between the dates is just a day (assuming the Time is identical). On closer inspection of DateDiff is shows that all the function was doing was

return (long)(calendar1.GetYear(Date2) - calendar1.GetYear(Date1));

Pants.

So I went off to look for a different approach. This when I came across this post in the Microsoft forums http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=958533&SiteID=1. I implemented the code as per Ti’s suggestion with one minor bug fix. Ti’s code always said that the time span between 3pm on 9 Dec 2006 and 10am on 11 Dec 2006 was two days. This is was because it was just subtracting the 11th from 9th, it needs to compare the hours like this

            if (this.toDate.Hour < this.fromDate.Hour)

            {

                // Not a full day so subtract fom the calculated days

                this.calculatedWholeDays--;

            }

To show it is just 1 day and 20 hours.