years Between - Java java.util

Java examples for java.util:Year

Description

years Between

Demo Code


import java.util.Calendar;
import java.util.Date;

public class Main{
    public static double yearsBetween(Date date1, Date date2) {
        return monthsBetween(date1, date2) / 12;
    }//w ww .  ja  v  a 2 s .c  o  m
    public static double monthsBetween(Date date1, Date date2) {
        Calendar calendar1 = DateUtils.calendar(date1);
        Calendar calendar2 = DateUtils.calendar(date2);

        int yearDiff = calendar2.get(Calendar.YEAR)
                - calendar1.get(Calendar.YEAR);
        int monthDiff = calendar2.get(Calendar.MONTH)
                - calendar1.get(Calendar.MONTH);
        int dayDiff = calendar2.get(Calendar.DATE)
                - calendar1.get(Calendar.DATE);

        return Math.abs(yearDiff * 12 + monthDiff + dayDiff / (double) 30);
    }
}

Related Tutorials