Date Difference in Years for .Net

Every now and then I’d need to calculate difference between two dates in terms of years and one would immediately think that you just subtract the first date from the second one and then use TotalYears property to get the value. My dear friends, have you ever looked at the properties of a TimeSpan?

There is TotalDays, TotalHours, TotalMinutes, TotalSeconds heck even TotalMilliseconds but no TotalMonths or TotalYears. So, I finally decided to search the almighty Google for it and immediately came across a question at StackOverflow and there was this answer from Richard J Ross III that solved my problem. What he basically did was add the resulting TimeSpan to a zero time (which is by the way at midnight of January 1, 0001 in Gregorian Calendar) and there you have it. The total number of years are now in the Year property of the resulting Date.

So, quickly I got an idea. Why not convert the given code into an Extension Method called TotalYears? That way, you can seamlessly integrate it into your date manipulation code and use it just like you’d use other properties.

Here is my extension method.

<Extension()> _
Public Function TotalYears(span As TimeSpan) As Integer
    Dim zeroTime As New Date(1, 1, 1)
    Return (zeroTime + span).Year - 1
End Function

And how to use it? Simple

Dim Date1 As New Date(2000, 1, 1)
Dim Date2 As New Date(2001, 1, 1)
MsgBox((Date2 - Date1).TotalYears)