How to calculate number of months between two dates in JAVA
There are many different ways one could calculate the number of months between two dates in JAVA. This is what I came up with.
- Create two GregorianCalendar obects as shown here
Calendar firstDate = new GregorianCalendar(2010, 10, 31); Calendar secondDate = new GregorianCalendar(2009, 12, 12);
- Now calculate the difference between these two Calendar objects
int months = (firstDate.get(Calendar.YEAR) - secondDate.get(Calendar.YEAR)) * 12 + (firstDate.get(Calendar.MONTH)- secondDate.get(Calendar.MONTH)) + (firstDate.get(Calendar.DAY_OF_MONTH) >= secondDate.get(Calendar.DAY_OF_MONTH)? 0: -1); System.out.println("Diff is.." + months);
It should display…. Diff is..10