TechMajik | Tips & hints for software developers

Jan/10

28

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 comments

  • Deepak · October 16, 2012 at 2:53 am

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

  • Martin Verner · December 18, 2012 at 9:13 am

    This doesn’t handle February very well…

  • dileep · January 8, 2013 at 8:56 am

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

Leave a Reply


6 + five =

<< Tag

Theme Design by devolux.nh2.me