Java Day Between truncateDifferMonths(Date date)

Here you can find the source of truncateDifferMonths(Date date)

Description

truncate Differ Months

License

Apache License

Declaration

public static int truncateDifferMonths(Date date) 

Method Source Code

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

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

public class Main {

    public static int truncateDifferMonths(Date date) {
        return truncateDifferMonths(date, new Date());
    }/*from   w  w  w. j  a va 2  s . c  o  m*/

    public static int truncateDifferMonths(Date date1, Date date2) {
        return calculateDifferMonths(date1, date2, true);
    }

    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 {
            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. monthsDiff(final Date data1, final Date data2)
  2. stdNewDate(String tzDiff)
  3. substractDate(final Date date, final Integer different)
  4. timeDifferenceInSeconds(Date startDate, Date endDate)
  5. timeDifferenceWithCurrentTime(Date startTime)
  6. yearDifference(Date date1, Date date2)
  7. yearTimeDiff(Date d1, Date d2)