Java Date Compare by Month monthsBetween(final Date von, final Date bis)

Here you can find the source of monthsBetween(final Date von, final Date bis)

Description

months Between

License

Open Source License

Declaration

public static Integer monthsBetween(final Date von, final Date bis) 

Method Source Code

//package com.java2s;

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

public class Main {

    public static Integer monthsBetween(final Date von, final Date bis) {

        if (von == null || bis == null) {
            return null;
        }/*from  w  ww . j ava2s .c  o  m*/

        if (bis.before(von)) {
            return null;
        }

        final Calendar calStart = Calendar.getInstance();
        calStart.setTime(von);
        setTimeTo0(calStart);

        final Calendar calEnde = Calendar.getInstance();
        calEnde.setTime(bis);
        setTimeTo0(calEnde);

        int anzMonthsBetween = 0;

        while (!isSameMonth(calStart.getTime(), calEnde.getTime())) {
            calStart.add(Calendar.MONTH, 1);
            anzMonthsBetween++;
        }
        return anzMonthsBetween;
    }

    private static void setTimeTo0(final Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    }

    public static boolean isSameMonth(final Date date1, final Date date2) {
        if (!isSameYear(date1, date2)) {
            return false;
        }
        final Calendar calStart = Calendar.getInstance();
        calStart.setTime(date1);
        final int monatVon = calStart.get(Calendar.MONTH);

        final Calendar calEnde = Calendar.getInstance();
        calEnde.setTime(date2);
        final int monatBis = calEnde.get(Calendar.MONTH);

        if (monatVon == monatBis) {
            return true;
        }
        return false;
    }

    public static boolean isSameYear(final Date date1, final Date date2) {
        if (date1 == null || date2 == null) {
            return date1 == date2; // NOPMD
        }
        final Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        final Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);

        return (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR));
    }
}

Related

  1. isSameMonth(Date date1, Date date2)
  2. isSameMonth(Date date1, Date date2)
  3. isSameMonth(final Date d1, final Date d2)
  4. isSameMonth(final Date date1, final Date date2)
  5. monthsBetween(Date firstDate, Date secondDate)
  6. sameMonth(Date date1, Date date2)
  7. sameMonth(Date date1, Date date2)
  8. sameMonth(Date dateOne, Date dateTwo)
  9. sameMonthYear(Date firstDate, Date secondDate)