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));
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With