Date difference in years using C#

msbyuva picture msbyuva · Nov 8, 2010 · Viewed 169.5k times · Source

How can I calculate date difference between two dates in years?

For example: (Datetime.Now.Today() - 11/03/2007) in years.

Answer

Richard J. Ross III picture Richard J. Ross III · Nov 8, 2010

I have written an implementation that properly works with dates exactly one year apart.

However, it does not gracefully handle negative timespans, unlike the other algorithm. It also doesn't use its own date arithmetic, instead relying upon the standard library for that.

So without further ado, here is the code:

DateTime zeroTime = new DateTime(1, 1, 1);

DateTime a = new DateTime(2007, 1, 1);
DateTime b = new DateTime(2008, 1, 1);

TimeSpan span = b - a;
// Because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;

// 1, where my other algorithm resulted in 0.
Console.WriteLine("Yrs elapsed: " + years);