### Thread: Number of months between 2 dates

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2004
Posts
2
Rep Power
0

#### Number of months between 2 dates

Hello,

How can I get the number of months between 2 Dates with Java Calendar object ?

Thanks and Regards from Switzerland !
2. No Profile Picture
Contributing User
Devshed Novice (500 - 999 posts)

Join Date
Jan 2004
Location
England
Posts
952
Rep Power
14
Code:
```Calendar cal1 = ...;
Calendar cal2 = ...;
....
int yearDiff = cal1.get(Calendar.YEAR)-cal2.get(Calendar.YEAR);
int monthDiff = cal1.get(Calendar.MONTH)-cal2.get(Calendar.MONTH)+12*yearDiff;```
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2004
Posts
2
Rep Power
0

#### Thanks!

4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2013
Posts
1
Rep Power
0

#### Greeting

Thank you so much rossM
5. No Profile Picture
Contributing User
Devshed Frequenter (2500 - 2999 posts)

Join Date
Nov 2004
Location
Washington DC
Posts
2,756
Rep Power
1571
For the given solution, would you expect this to pass or fail?

Code:
``` @Test
public void testCalendarBasedMonthDifference()
{
Calendar cal1 = Calendar.getInstance();
cal1.set(2013, Calendar.JANUARY, 1);
Calendar cal2 = Calendar.getInstance();
cal2.set(2013, Calendar.FEBRUARY, 2);
int yearDiff = cal1.get(Calendar.YEAR)-cal2.get(Calendar.YEAR);
int monthDiff = cal1.get(Calendar.MONTH)-cal2.get(Calendar.MONTH)+12*yearDiff;

assertEquals(1, monthDiff);
}```
Date manipulation is deceptively hard! Let someone else do the work for you and use jodaTime. Besides, it's cleaner!

Code:
```    @Test
public void testJodaBasedMonthDifference()
{
LocalDate cal1 = new LocalDate(2013, DateTimeConstants.JANUARY, 1);
LocalDate cal2 = new LocalDate(2013, DateTimeConstants.FEBRUARY, 1);
int monthDiff = Months.monthsBetween(cal1, cal2).getMonths();
assertEquals(1, monthDiff);
}```
6. No Profile Picture
Super Moderator
Devshed Specialist (4000 - 4499 posts)

Join Date
Jul 2003
Posts
4,009
Rep Power
2791
I'm hoping that after 9 years they have either found the solution or moved on, tfecw.

I realise that the thread was bumped before you replied