Sunday, January 23, 2011

Java code to calculate number of months between two different given date as done by oracle monthsbetween function

Many of the times we came across the situation when need to calculate the number of months between two date.The following program demonstrates how to calculate difference between two dates in terms of month.

Logic to calculate the number of months between two dates


In order to find the difference between two dates in terms month we have to find the three factors that produce the result.

First the difference of years between those dates and multiplying that with 12 return the difference in months for years.

Then we find the difference for the months of those dates.

To find the difference of months due to the day of the dates we check whether the days are last day of months or not. If both are last days of months then the factor is zero otherwise we calculate the difference of the days and divide by 31 because in oracle months_between function it calculates 31 day a month.

Finally we just add up these three factors which provide the desired result.

Example to find months between two distinct dates


First date 05/02/2011
Second date 25/01/2010
So the factors are
F1 = (2011-2010)*12 = 12
F2 = 2-1 = 1
F3 = (5-25)/31 = -0.6451612903225806
So the result becomes
= F1 + F2 + F3
= 12 + 1 + (-0.64516129)
= 12.35483870967742

Source code to find the number of months between two dates




import java.util.Calendar;
import java.util.GregorianCalendar;

public class JavaMonthsBetweenTwoDateExample {

public static void main(String[] args) {
//creation of calendar object to call the method
//new GregorianCalendar(yyyy, mm, dd) here month 0 is for January
Calendar date1 = new GregorianCalendar(2011, 1, 5);
Calendar date2 = new GregorianCalendar(2010, 0, 25);
double monthsBetween = monthsBetween(date1, date2);
System.out.println("Number of months between two date is "+monthsBetween);
System.out.println("Number of months between two date is "+(int)monthsBetween);
}

public static double monthsBetween(Calendar date1, Calendar date2){
double monthsBetween = 0;
//difference in month for years
monthsBetween = (date1.get(Calendar.YEAR)-date2.get(Calendar.YEAR))*12;
//difference in month for months
monthsBetween += date1.get(Calendar.MONTH)-date2.get(Calendar.MONTH);
//difference in month for days
if(date1.get(Calendar.DAY_OF_MONTH)!=date1.getActualMaximum(Calendar.DAY_OF_MONTH)
&& date1.get(Calendar.DAY_OF_MONTH)!=date1.getActualMaximum(Calendar.DAY_OF_MONTH) ){
monthsBetween += ((date1.get(Calendar.DAY_OF_MONTH)-date2.get(Calendar.DAY_OF_MONTH))/31d);
}
return monthsBetween;
}

}



Output of the above program


Number of months between two date is 12.35483870967742
Number of months between two date is 12


No comments:

Post a Comment