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
6
  • 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. May 31, 2012 at 8:15
  • 3
  • 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. May 31, 2012 at 8:17
  • @David Brabant thanks you so much for your link .
    – lelewin
    May 31, 2012 at 8: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, 2012 at 8:39

2 Answers 2

14

This will give difference between months:

int months = (Date2.Year - Date1.Year) * 12 + Date2.Month - Date1.Month;
3
  • 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. May 31, 2012 at 8: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, 2012 at 8: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, 2012 at 9: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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.