Java Day Between yearDifference(Date date1, Date date2)

Here you can find the source of yearDifference(Date date1, Date date2)

Description

date2-date1 if either are null, it returns null.

License

Open Source License

Declaration

public static Integer yearDifference(Date date1, Date date2) 

Method Source Code

//package com.java2s;
/**//from   w  w  w  .  ja  v a  2 s . com
 * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
 * This software is published under the GPL GNU General Public License.
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version. 
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * This software was written for the
 * Department of Family Medicine
 * McMaster University
 * Hamilton
 * Ontario, Canada
 */

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

public class Main {
    /**
     * date2-date1
     * 
     * if either are null, it returns null.
     */
    public static Integer yearDifference(Date date1, Date date2) {
        if (date1 == null || date2 == null)
            return (null);

        Calendar cal1 = new GregorianCalendar();
        cal1.setTime(date1);

        Calendar cal2 = new GregorianCalendar();
        cal2.setTime(date2);

        return (yearDifference(cal1, cal2));
    }

    /**
     * date2-date1
     * 
     * if either are null, it returns null.
     */
    public static Integer yearDifference(Calendar date1, Calendar date2) {
        if (date1 == null || date2 == null)
            return (null);

        int yearDiff = date2.get(Calendar.YEAR) - date1.get(Calendar.YEAR);

        if (date2.get(Calendar.MONTH) > date1.get(Calendar.MONTH))
            yearDiff--;
        else if (date2.get(Calendar.MONTH) == date1.get(Calendar.MONTH)
                && date2.get(Calendar.DAY_OF_MONTH) < date1.get(Calendar.DAY_OF_MONTH))
            yearDiff--;

        return (yearDiff);
    }
}

Related

  1. stdNewDate(String tzDiff)
  2. substractDate(final Date date, final Integer different)
  3. timeDifferenceInSeconds(Date startDate, Date endDate)
  4. timeDifferenceWithCurrentTime(Date startTime)
  5. truncateDifferMonths(Date date)
  6. yearTimeDiff(Date d1, Date d2)