Java Date Between getBetweenMonths(Date date1, Date date2)

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

Description

get Between Months

License

Apache License

Declaration

public static int getBetweenMonths(Date date1, Date date2) 

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 getBetweenMonths(Date date1, Date date2) {
        int iMonth = 0;
        int flag = 0;
        Calendar objCalendarDate1 = Calendar.getInstance();
        objCalendarDate1.setTime(date1);

        Calendar objCalendarDate2 = Calendar.getInstance();
        objCalendarDate2.setTime(date2);

        if (objCalendarDate2.equals(objCalendarDate1))
            return 0;
        if (objCalendarDate1.after(objCalendarDate2)) {
            Calendar temp = objCalendarDate1;
            objCalendarDate1 = objCalendarDate2;
            objCalendarDate2 = temp;//www . j  a v a 2s  . c o  m
        }
        if (objCalendarDate2.get(Calendar.DAY_OF_MONTH) < objCalendarDate1.get(Calendar.DAY_OF_MONTH))
            flag = 1;

        if (objCalendarDate2.get(Calendar.YEAR) > objCalendarDate1.get(Calendar.YEAR))
            iMonth = ((objCalendarDate2.get(Calendar.YEAR) - objCalendarDate1.get(Calendar.YEAR)) * 12
                    + objCalendarDate2.get(Calendar.MONTH) - flag) - objCalendarDate1.get(Calendar.MONTH);
        else
            iMonth = objCalendarDate2.get(Calendar.MONTH) - objCalendarDate1.get(Calendar.MONTH) - flag;

        return iMonth;
    }
}

Related

  1. getBetweenDate(Date startDate, Date endDate)
  2. getBetweenDate(String d1, String d2)
  3. getBetweenDateBuckets(Date from, Date to)
  4. getBetweenDates(Date fromDate, Date toDate )
  5. getBetweenDays(String strFromDate, String strToDate)
  6. getBetweenTime(Date begin, Date end, int field)
  7. getBetweenWorkDate(int amount, Date beginDate)
  8. isBetween(Date check, Date from, Date to)
  9. isBetween(Date date, Date d1, Date d2)