This code works even when number of days between two dates are 365 days. E.g. 29th February 1972 and 28. February 1973, then it will return 0 years and 11 months.
if (endDate < startDate)
{
DateTime temp = endDate;
endDate = startDate;
startDate = temp;
}
years = endDate.Year - startDate.Year;
months = endDate.Month - startDate.Month;
int days = endDate.Day - startDate.Day;
if (days < 0) months--;
if (months < 0)
{
months += 12;
years--;
}
By the way, you need to remove the two lines to make the out parameters work correctly:
int years=0;
int months=0;