Get difference between two dates in months using Java

date, java

Solution

If you can't use JodaTime, you can do the following:

Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);

int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);

Note that if your dates are 2013-01-31 and 2013-02-01, you get a distance of 1 month this way, which may or may not be what you want.

Problem

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)); ```

Original source

Related problems