2

I have two java.sql.Date objects, and I need to calculate the number of months between the two. This should take into account percentage of months. For instance 10/1/2012 to 11/15/2012 should return 1.5 months. Is there an available library that can do this for me? Any recommendations?

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
Jay
  • 4,994
  • 4
  • 28
  • 41

2 Answers2

3

This is similar to another question to calculate the number of days between two dates. With the number of days, you can divide by the average number of days per month to get a representation of how many months have passed. Something like Joda Time can provide that information.

Re: http://joda-time.sourceforge.net/ Re: Difference in days between two dates in Java?

Community
  • 1
  • 1
Bob
  • 31
  • 1
1

I would convert to java.util.Date and then do the calculation

Somthing like this:

private final static double AVERAGE_MILLIS_PER_MONTH = 365.24 * 24 * 60 * 60 * 1000 / 12;

public static double monthsBetween(Date d1, Date d2) {
    return (d2.getTime() - d1.getTime()) / AVERAGE_MILLIS_PER_MONTH; 
}
Frank
  • 16,476
  • 7
  • 38
  • 51