4

I am doing this

datediff = (date1 - DateOfDeposit).TotalDays;

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

James
  • 172
  • 2
  • 10
  • possible duplicate of [Difference in months between two dates](http://stackoverflow.com/questions/4638993/difference-in-months-between-two-dates) – Edward Brey Sep 14 '15 at 13:09

2 Answers2

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

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.

Ani
  • 111,048
  • 26
  • 262
  • 307
  • If dateOfDeposit is later than date1 the result will be negative. Should be int m = 12 * (DateOfDeposit.Year - date1.Year) + (DateOfDeposit.Month - date1.Month); – Jade Dec 19 '13 at 06:58
  • 1
    That will treat (say) June 30th to July 1st as the same number of months as June 1st to July 31st. I'd say that the first is 0 months and 1 day, whereas the second is 1 month and 30 days. I'm not quite sure what *you* mean by "whole months", but I'd say there's a whole month between June 1st and July 31st, but there isn't a whole month between June 30th and July 1st... – Jon Skeet Dec 19 '13 at 06:59
  • Yes, Jon. I indeed meant to treat (Any day in July - Any day in June) = 1 month. The OP's requirements aren't clear, but this is at least precise to define. Otherwise, it's not at all clear how to treat Feb 28 - Jan 29, for example. Is it 0 months and 30 days? Or is it 1 month and 2 days (2 days in January + all of February, assuming not a leap year). Or is it (2/31 + 28/28) months? Not easy to define without precise requirements. `Period.Between(start, end, PeriodUnits.Months)` does *look* nice though, complications of definition aside. – Ani Dec 19 '13 at 07:40