Java Month Get getIntevalMonth(String strDate1, String strDate2)

Here you can find the source of getIntevalMonth(String strDate1, String strDate2)

Description

get Inteval Month

License

Open Source License

Declaration

public static int getIntevalMonth(String strDate1, String strDate2) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {

    public static int getIntevalMonth(String strDate1, String strDate2) {
        int iMonth = 0;
        int flag = 0;
        try {/*from w w  w. j ava 2  s.  c  o  m*/
            Calendar objCalendarDate1 = Calendar.getInstance();
            objCalendarDate1.setTime(DateFormat.getDateInstance().parse(strDate1));

            Calendar objCalendarDate2 = Calendar.getInstance();
            objCalendarDate2.setTime(DateFormat.getDateInstance().parse(strDate2));

            if (objCalendarDate2.equals(objCalendarDate1))
                return 0;
            if (objCalendarDate1.after(objCalendarDate2)) {
                Calendar temp = objCalendarDate1;
                objCalendarDate1 = objCalendarDate2;
                objCalendarDate2 = temp;
            }
            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;
            }
        } catch (Exception e) {
            System.err.print(e);
        }
        return iMonth;
    }

    public static Date parse(String strDate, String pattern) throws ParseException {
        try {
            return getFormatter(pattern).parse(strDate);
        } catch (ParseException pe) {
            throw new ParseException("Method parse in Class DateUtil  err: parse strDate fail.",
                    pe.getErrorOffset());
        }
    }

    private static SimpleDateFormat getFormatter(String parttern) {
        return new SimpleDateFormat(parttern);
    }
}

Related

  1. getCurMonth2Long()
  2. getCurrMonthLastDay()
  3. getEndDateOfMonth(String yyyymmdd)
  4. getEngMonth()
  5. getIntervalMonths(String startDate, String endDate)
  6. getMonth()
  7. getMonth()
  8. getMonth()
  9. getMonth()