[java] Get difference between two dates in months using Java

I need to get difference between two dates using Java. I need my result to be in months.

Example:

Startdate = 2013-04-03 enddate = 2013-05-03 Result should be 1

if the interval is

Startdate = 2013-04-03 enddate = 2014-04-03 Result should be 12

Using the following code I can get the results in days. How can I get in months?

Date startDate = new Date(2013,2,2);
Date endDate = new Date(2013,3,2);
int difInDays = (int) ((endDate.getTime() - startDate.getTime())/(1000*60*60*24));

This question is related to java date

The answer is


You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

You can try this:

Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);

I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar from a Date and just get the month's diff.