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.    
 
 
 
  1. Create two GregorianCalendar obects as shown here
    Calendar firstDate = new GregorianCalendar(2010, 10, 31);
    Calendar secondDate = new GregorianCalendar(2009, 12, 12);    
    

         

  2. 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   

    

 

  

 

   

 

Tags:

3 Responses to “How to calculate number of months between two dates in JAVA”

  1. Deepak says:

    its not working for these dates:
    Calendar firstDate = new GregorianCalendar(2012, 05,05);
    Calendar secondDate = new GregorianCalendar(2012,02,05);

  2. This doesn’t handle February very well…

  3. dileep says:

    that is giving Diff as 11 (Used java 1.6 –> jdk160_05)

Leave a Reply


3 − two =