Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
June 16th, 2004, 09:30 AM
 Fr@ncky
Registered User

Join Date: Jun 2004
Posts: 2
Time spent in forums: < 1 sec
Reputation 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
June 16th, 2004, 10:51 AM
 rossM
Contributing User

Join Date: Jan 2004
Location: England
Posts: 952
Time spent in forums: 4 Days 23 h 38 m 44 sec
Reputation Power: 13
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
June 17th, 2004, 02:37 AM
 Fr@ncky
Registered User

Join Date: Jun 2004
Posts: 2
Time spent in forums: < 1 sec
Reputation Power: 0
Thanks!

#4
June 2nd, 2013, 09:49 AM
 kanna@enhances
Registered User

Join Date: Jun 2013
Posts: 1
Time spent in forums: 11 m 11 sec
Reputation Power: 0
Greeting

Thank you so much rossM

#5
June 6th, 2013, 08:12 AM
 tfecw
Contributing User

Join Date: Nov 2004
Location: Washington DC
Posts: 2,756
Time spent in forums: 3 Months 1 Week 3 Days 8 h 50 m 10 sec
Reputation 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);
}```
__________________
Open for extension, closed for modification

#6
June 6th, 2013, 10:57 AM
 Winters
Super Moderator

Join Date: Jul 2003
Posts: 4,002
Time spent in forums: 1 Month 2 Weeks 4 Days 4 h 12 m 7 sec
Reputation Power: 2726
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
__________________
[PHP] | [Perl] | [Python] | [Java] != [JavaScript] | [XML] | [ANSI C] | [C++] | [LUA] | [MySQL] | [FirebirdSQL] | [PostgreSQL] | [HTML] | [XHTML] | [CSS]

W3Fools - A W3Schools Intervention.

 Viewing: Dev Shed Forums > Programming Languages > Java Help > Number of months between 2 dates