Java Day Between monthDiff(Date fromDate, Date toDate)

Here you can find the source of monthDiff(Date fromDate, Date toDate)

Description

month Diff

License

Open Source License

Declaration

public static int monthDiff(Date fromDate, Date toDate) 

Method Source Code

//package com.java2s;

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

public class Main {
    public static final long LONG_DAY = 1000 * 24 * 60 * 60;
    public static final int DAY_PER_MONTH = 30;

    public static int monthDiff(Date fromDate, Date toDate) {
        long dateDiff = dateDiff(fromDate, toDate);

        int monthDiff = (int) (dateDiff / DAY_PER_MONTH);

        if (addMonths(fromDate, monthDiff).after(toDate)) {
            monthDiff--;//from   w ww.j ava 2 s  .com
        }

        return monthDiff;
    }

    public static int dateDiff(Date fromDate, Date toDate) {
        long diff = toDate.getTime() - fromDate.getTime();

        return (int) (diff / LONG_DAY) + 1;
    }

    /**
     * Add month to the date.
     * 
     * @param date
     * @param amount
     * @return
     */
    public static Date addMonths(Date date, int amount) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, amount);
        return calendar.getTime();
    }
}

Related

  1. getYearsDifference(Date startTime, Date endTime)
  2. hourDiff(Date firstDate, Date lastDate)
  3. internalTrimOrAlterDate(Date date, boolean trim, int dayDiff)
  4. monthDiff(Date beginDate, Date endDate)
  5. monthDiff(Date from, Date to)
  6. monthDifference(final Date a, final Date b)
  7. monthsDiff(final Date data1, final Date data2)
  8. stdNewDate(String tzDiff)
  9. substractDate(final Date date, final Integer different)