Getting the years between 2 dates

I needed to get the years between 2 dates. When taking 2 dates and subtracting the one from the other it returns a TimeSpan. The timespan does not contain a Years or TotalYears property or method.

To get to the needed result I have created the following method:

private int GetYears(DateTime dtm) {

       TimeSpan ts = DateTime.Today.Subtract(dtm);

 

      // Used to calc start year

     int adjustYears = 4;

 

     for (int i = 4 – 1; i >= 0; i—) {

         if (DateTime.DaysInMonth(dtm.Year – i, 2) == 29) {

              adjustYears += i;

              break;

         }

     }

 

     return new DateTime().AddYears(adjustYears – 1).AddDays(Math.Abs(ts.TotalDays)).Year –

                            adjustYears;

}

Comments are closed.