I am doing this
datediff = (date1 - DateOfDeposit).TotalDays;
But this gives the no. of days and I want no.of months.
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.
Assuming you want the number of whole months, I think this should work (not sure what corner-cases this doesn't handle, but can't think of any off the top of my head):
12 * (date1.Year - DateOfDeposit.Year) + (date1.Month - DateOfDeposit.Month)
You could always add any fractional component with DateTime.Day, but it's not clear how that should precisely be defined (how many months are between Jan 29 and Feb 27?).
If you're doing a lot of date-time handling, Jon Skeet's Noda Time library (that he mentions in his answer) is a good choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With