donderdag 19 juli 2012

Difference between 2 dates in C#

I tried to do a simple DateTime calculation in C#. What I wanted to achieve is to know how many years, months and days where between 2 DateTime variables. Or at least I thought this would be easy. Turns out there is know real out-of-the-box functionality available to handle this in C#.

The only thing available out-of-the-box in C# is using TimeSpan. Unfortuanately the only calculations TimeSpan can return is the number of days, hours, minutes, seconds and milliseconds. But how about the years, months and days than?

Here's a simple method to show the possibilities of the TimeSpan:
public void PrintDateDiffUsingTimeSpan(DateTime begin, DateTime end)
            TimeSpan span = end - begin;

            StringBuilder str = new StringBuilder();
            str.Append("Total span: ");
            str.Append(span.Days + " days, ");
            str.Append(span.Hours + " hours, ");
            str.Append(span.Minutes + " minutes, ");
            str.Append(span.Seconds + " seconds, ");
            str.Append(span.Milliseconds + " milliseconds");

            Console.WriteLine(str.ToString() + "\n");

            Console.WriteLine("Total Days: " + span.TotalDays);
            Console.WriteLine("Total Hours: " + span.TotalHours);
            Console.WriteLine("Total Minutes: " + span.TotalMinutes);
            Console.WriteLine("Total Seconds: " + span.TotalSeconds);
            Console.WriteLine("Total Milliseconds: " + span.TotalMilliseconds);

I ended up using a freely available .NET library called 'Time Period'. The source code can be found here. There's also an on line demo and documentation available.
Here's a simple method to show some the possibilities of the TimeSpan:

  public void PrintDateDiff(DateTime begin, DateTime end)
            DateDiff diff = new DateDiff(begin, end);
            StringBuilder str = new StringBuilder();
            str.Append("Total difference: ");
            str.Append(diff.ElapsedYears + " years, ");
            str.Append(diff.ElapsedMonths + " months, ");
            str.Append(diff.ElapsedDays + " days");

            Console.WriteLine(str.ToString() + "\n");

            Console.WriteLine("Total Days: " + diff.Days);
            Console.WriteLine("Total Weeks: " + diff.Weeks);
            Console.WriteLine("Total Weekdays: " + diff.Weekdays);
            Console.WriteLine("Total Quarters: " + diff.Quarters);
            Console.WriteLine("Total Hours: " + diff.Hours);

There are much more possibilities in the DateDiff class of the Time Period library. There are even much more classes available in the library. To know more of the capabilities of this library I again refer to the documentation.


2 opmerkingen:

  1. simply do like this

    String diff2 = (secondDate - firstDate).TotalDays.ToString();


    1. Actually, this would only return the difference in days... I needed the years, months, etc. seperately.