How to calculate the number of months between two dates in C#

I am doing this

datediff = (date1 - DateOfDeposit).TotalDays;

But this gives the no. of days and I want no.of months.

Jon Skeet
people
quotationmark

The simplest option is probably to use my Noda Time library, which was designed for exactly this sort of thing (as well as making it cleaner to work with dates and times in general):

LocalDate start = new LocalDate(2013, 1, 5);
LocalDate end = new LocalDate(2014, 6, 1);
Period period = Period.Between(start, end, PeriodUnits.Months);
Console.WriteLine(period.Months); // 16

There's nothing built into .NET to make this particularly easy. You could subtract years and months as per Ani's answer, but then also take the day of month into account to avoid the issue I describe in comments. I'd suggest writing a good set of unit tests first though - bearing in mind leap years and the like.

people

See more on this question at Stackoverflow