12

I would like to know how to calculate the numbers of Month between two dates. Is there any method to calculate it in C#?

Eg1.    Date1 = "2011/11/01"  
        Date2 = "2012/02/01"     
Result. Numbers of Month =3  

 Eg2.  Date1 = "2012/01/31"
       Date2 = "2012/02/01"  
Result. Numbers of Month =1

 Eg3.  Date1 = "2012/01/01"  
       Date2 = "2012/02/28"
 Result. Numbers of Month =1
Mike G
  • 4,232
  • 9
  • 40
  • 66
lelewin
  • 559
  • 2
  • 10
  • 26
  • 2
    How about a few more test cases? Your problem is underspecified. This is one of the problems where figuring out what you want is harder than implementing it. – CodesInChaos May 31 '12 at 08:15
  • 3
    http://stackoverflow.com/questions/1525990/difference-in-months – David Brabant May 31 '12 at 08:16
  • 1
    First you should have a clear idea of what is "the numbers of months between two dates". Like 2012-01-25 to 2012-02-01 or to 2012-02-24 etc. If you do, check the answers if they are consistent with your idea. – Eugene Ryabtsev May 31 '12 at 08:17
  • @David Brabant thanks you so much for your link . – lelewin May 31 '12 at 08:19
  • @Eugene Ryabtsev : thanks you so much . I want to know only month. if the two dates are 2012-01-25 and 2012-02-01 , I want the result is 1.And also 202-01-25 and 2012-02-24 case, I want the result 1. – lelewin May 31 '12 at 08:39
  • @lelewin http://bytes.com/topic/c-sharp/answers/255923-difference-between-two-dates-month or http://stackoverflow.com/questions/1083955/how-to-get-difference-between-two-dates-in-year-month-week-day – Neha May 31 '12 at 08:47

2 Answers2

14

This will give difference between months:

int months = (Date2.Year - Date1.Year) * 12 + Date2.Month - Date1.Month;
Tschareck
  • 4,071
  • 9
  • 47
  • 74
  • 3
    That's a possible answer, depending on what the OP actually wants. For example this will return 1 for MonthBetween(2012-06-01, 2012-05-31), which may or may not be what the OP wants. – CodesInChaos May 31 '12 at 08:22
  • 1
    That doesn't take the day of month into account at all though. For example, it will give the same number of months between May 31 and June 1st as between May 1st and June 31st. I don't think many people would expect that result. – Jon Skeet May 31 '12 at 08:23
  • @Jon Skeet : I am deeply sorry for my unclear question. I doesn't want to take the day of month into account at all though because of system requirements. Now I have edited my question . – lelewin May 31 '12 at 09:36
9

My Noda Time project provides for this:

LocalDate date1 = new LocalDate(2011, 11, 1);
LocalDate date2 = new LocalDate(2012, 2, 1);
Period period = Period.Between(date1, date2, PeriodUnits.Months);
long months = period.Months; // 3

See the project documentation for arithmetic for more information.

Carl
  • 5,881
  • 4
  • 25
  • 24
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194