0

I am trying to find calendar number of months between two dates using C#.

Eg1 : dt1 :09-31-2016 dt2 : 10-02-2016 Result : 2 (1 for September + 1 for October)

Eg2 : dt1 :08-31-2016 dt2 : 01-02-2017 Result : 6

I am using the below code but not able to achieve the result

var difference = ((dt1.Year - dt2.Year) * 12) + (dt1.Month - dt2.Month);

Please help me

Eric Sondergard
  • 565
  • 5
  • 22
bhavya158
  • 29
  • 1
  • 10
  • Try swapping the dates - looks like you are subtracting the later date from the earlier date – PaulF Nov 01 '16 at 16:20
  • This is different from the link you have provided – bhavya158 Nov 01 '16 at 16:21
  • Seems like you just want to add 1 to the difference. 10 - 9 = 1 but you want 2. – juharr Nov 01 '16 at 16:24
  • Thanks Paul & Juhhar. Wanted to see if there is better way than this – bhavya158 Nov 01 '16 at 16:27
  • Well [last time this question was posted](http://stackoverflow.com/questions/14290776/calculate-the-number-of-calendar-months-between-two-dates) it was closed as a duplicate and I don't see how yours is different. There are [plenty of answers on this question](http://stackoverflow.com/questions/4638993/difference-in-months-between-two-dates) already. – Equalsk Nov 01 '16 at 16:28

1 Answers1

2

This should give the answer you want

((dt2.Year - dt1.Year) * 12) + (dt2.Month - dt1.Month) + 1
PaulF
  • 6,673
  • 2
  • 18
  • 29