Java Day Between calculateDifferMonths(Date date1, Date date2, boolean isTruncate)

Here you can find the source of calculateDifferMonths(Date date1, Date date2, boolean isTruncate)

Description

calculate Differ Months

License

Apache License

Declaration

private static int calculateDifferMonths(Date date1, Date date2,
        boolean isTruncate) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

public class Main {

    private static int calculateDifferMonths(Date date1, Date date2,
            boolean isTruncate) {
        final int[] bgnDate, endDate;
        if (date1.getTime() > date2.getTime()) {
            bgnDate = getYearMonthDay(date2);
            endDate = getYearMonthDay(date1);
        } else {// w  ww .ja va 2  s  .  c om
            bgnDate = getYearMonthDay(date1);
            endDate = getYearMonthDay(date2);
        }

        final int endMonth;
        if (!isTruncate || endDate[2] >= bgnDate[2]) {
            endMonth = endDate[1];
        } else {
            endMonth = endDate[1] - 1;
        }

        if (endMonth >= bgnDate[1]) {
            return (endDate[0] - bgnDate[0]) * 12 + (endMonth - bgnDate[1]);
        } else {
            return (endDate[0] - bgnDate[0] - 1) * 12
                    + (12 + endMonth - bgnDate[1]);
        }
    }

    public static int[] getYearMonthDay(Date date) {
        Calendar bgnDate = Calendar.getInstance();
        bgnDate.setTime(date);
        return new int[] { bgnDate.get(Calendar.YEAR),
                bgnDate.get(Calendar.MONTH) + 1, bgnDate.get(Calendar.DATE) };
    }
}

Related

  1. calculateDayDifference(final Date a, final Date b)
  2. calculateDays(Date beginDate, Date endDate)
  3. calculateDays(Date dateEarly, Date dateLater)
  4. calculateDifference(Date d1, Date d2)
  5. calculateNumberOfDays(String dateStr)
  6. countDiffDay(String beginDateBase, String endDateBase)
  7. dayDiff(Date d1, Date d2)
  8. dayDiff(Date start, Date end)