Monday, April 7, 2014

Calculate Number of Years between 2 Calendar Dates

Here is a function that calculates the number of years between 2 calendar dates:

public static double  yearsBetween(Calendar cal1, Calendar cal2){
        double dmsyear = 1000L * 60 * 60 * 24 * 365;
        return (cal1.getTimeInMillis()- cal2.getTimeInMillis())/dmsyear;
}   

You could call the method and format the result as String as follows:

Calendar cal1 = GregorianCalendar.getInstance();
Calendar cal2 = GregorianCalendar.getInstance();
cal2.set(2009,7,1);
String.format("%.1f years", yearsBetween(cal1, cal2));

Related posts:
Determine Next Month in Java

No comments:

Post a Comment