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   

    

 

  

 

   

 

3 thoughts on “How to calculate number of months between two dates in JAVA

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

Leave a Reply

Your email address will not be published. Required fields are marked *


seven − 1 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>