Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find number of months between two date range in java using calender api

Tags:

java

I have two dates (01/01/2012, 31/07/2014).

Would you please help me to calculate month difference between this two dates. If difference is 8 months 1 days i need result 9 months.

like image 303
John Avatar asked Dec 17 '25 17:12

John


1 Answers

Working Code:

public int monthsBetweenDates(Date startDate, Date endDate){

        Calendar start = Calendar.getInstance();
        start.setTime(startDate);

        Calendar end = Calendar.getInstance();
        end.setTime(endDate);

          int monthsBetween = 0;
            int dateDiff = end.get(Calendar.DAY_OF_MONTH)-start.get(Calendar.DAY_OF_MONTH);      

if(dateDiff<0) {
                int borrrow = end.getActualMaximum(Calendar.DAY_OF_MONTH);           
                 dateDiff = (end.get(Calendar.DAY_OF_MONTH)+borrrow)-start.get(Calendar.DAY_OF_MONTH);
                 monthsBetween--;

if(dateDiff>0) {
                     monthsBetween++;
                 }
            }
            else {
                monthsBetween++;
            }      
            monthsBetween += end.get(Calendar.MONTH)-start.get(Calendar.MONTH);      
            monthsBetween  += (end.get(Calendar.YEAR)-start.get(Calendar.YEAR))*12;      
            return monthsBetween;
     }
like image 75
Md. Kamruzzaman Avatar answered Dec 20 '25 08:12

Md. Kamruzzaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!