Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

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));
like image 758
ashu Avatar asked May 15 '13 07:05

ashu


2 Answers

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.

like image 109
Étienne Miret Avatar answered Oct 22 '22 04:10

Étienne Miret


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();
like image 4
MadTech Avatar answered Oct 22 '22 05:10

MadTech