Java Date Difference differenceInMonths(Date beginningDate, Date endingDate)

Here you can find the source of differenceInMonths(Date beginningDate, Date endingDate)

Description

calculate difference in months between the arguments.

License

Open Source License

Parameter

Parameter Description
beginningDate a parameter
endingDate a parameter

Return

number of months

Declaration

public static int differenceInMonths(Date beginningDate, Date endingDate) 

Method Source Code


//package com.java2s;
/*//  www .  j av a  2s  . c  o m
 * Copyright (C) 2015 B3Partners B.V.
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 */

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

public class Main {
    /**
     * calculate difference in months between the arguments.
     *
     * @param beginningDate
     * @param endingDate
     * @return number of months
     *
     * @see #differenceInMonths(java.util.Calendar, java.util.Calendar)
     */
    public static int differenceInMonths(Date beginningDate, Date endingDate) {
        if (beginningDate == null || endingDate == null) {
            return 0;
        }
        Calendar cal1 = new GregorianCalendar();
        cal1.setTime(beginningDate);
        Calendar cal2 = new GregorianCalendar();
        cal2.setTime(endingDate);
        return differenceInMonths(cal1, cal2);
    }

    /**
     * calculate difference in months between the arguments.
     *
     * @param beginningDate
     * @param endingDate
     * @return number of months
     */
    public static int differenceInMonths(Calendar beginningDate, Calendar endingDate) {
        if (beginningDate == null || endingDate == null) {
            return 0;
        }
        int m1 = beginningDate.get(Calendar.YEAR) * 12 + beginningDate.get(Calendar.MONTH);
        int m2 = endingDate.get(Calendar.YEAR) * 12 + endingDate.get(Calendar.MONTH);
        return m2 - m1;
    }
}

Related

  1. diffDay(Date startDate, Date endDate)
  2. differDays(Date src, Date target)
  3. difference(Date date1, Date date2)
  4. differenceDay(Date toDate, Date fromDate)
  5. DifferenceInMilliseconds(Date date1, Date date2)
  6. DifferenceInSeconds(Date date1, Date date2)
  7. differenceMonth(Date date1, Date date2)
  8. differenceOnMonth(Date date1, Date date2)
  9. differenceOnYear(Date date1, Date date2)