Java Date Difference differenceOnMonth(Date date1, Date date2)

Here you can find the source of differenceOnMonth(Date date1, Date date2)

Description

difference On Month

License

Open Source License

Declaration

public static int differenceOnMonth(Date date1, Date date2) 

Method Source Code

//package com.java2s;

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

public class Main {

    public static int differenceOnMonth(Date date1, Date date2) {
        if (date1 == null || date2 == null)
            return 0;

        int difYear = 0;
        int difMonth = 0;

        int year1 = getDateYear(date1);
        int year2 = getDateYear(date2);
        int month1 = getMonthOnDate(date1);
        int month2 = getMonthOnDate(date2);

        difYear = (year2 - year1) * 12;//from w  ww  .jav  a2  s  .c  o  m
        difMonth = month2 - month1;

        return Math.abs(difYear + difMonth);
    }

    public static int getDateYear(Date date) {
        if (date == null)
            return 0;

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.YEAR);
    }

    public static int getMonthOnDate(Date date) {
        if (date == null)
            return 0;

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        return cal.get(Calendar.MONTH);
    }
}

Related

  1. differenceDay(Date toDate, Date fromDate)
  2. DifferenceInMilliseconds(Date date1, Date date2)
  3. differenceInMonths(Date beginningDate, Date endingDate)
  4. DifferenceInSeconds(Date date1, Date date2)
  5. differenceMonth(Date date1, Date date2)
  6. differenceOnYear(Date date1, Date date2)
  7. diffIntoMilliSecond(java.util.Date date, java.util.Date date1)
  8. diffMillis(Date d1, Date d2)
  9. diffMonth(Date before, Date after)