Calculates difference in years between to dates. - Java java.util

Java examples for java.util:Year

Description

Calculates difference in years between to dates.

Demo Code

/*// w w w. j  a v  a2 s.  c o m
 * Copyright 2011 - 2012
 * All rights reserved. License and terms according to LICENSE.txt file.
 * The LICENSE.txt file and this header must be included or referenced 
 * in each piece of code derived from this project.
 */
//package com.java2s;

import java.util.Calendar;

public class Main {
    public static void main(String[] argv) throws Exception {
        Calendar a = Calendar.getInstance();
        Calendar b = Calendar.getInstance();
        System.out.println(differenceInYears(a, b));
    }

    private static final long MILLISECONDS_PER_YEAR = 365 * 24 * 60 * 60
            * 1000;

    /**
     * Calculates difference in years between to dates.
     * @param a first element of substraction of dates.
     * @param b second element of substraction of dates.
     * @return a-b in fractions of year.
     */
    public static double differenceInYears(final Calendar a,
            final Calendar b) {
        final long millisDif = a.getTimeInMillis() - b.getTimeInMillis();
        return millisDif / MILLISECONDS_PER_YEAR;
    }
}

Related Tutorials