Java Month Get getIntervalMonths(String startDate, String endDate)

Here you can find the source of getIntervalMonths(String startDate, String endDate)

Description

get Interval Months

License

Open Source License

Declaration

public static int getIntervalMonths(String startDate, String endDate) 

Method Source Code

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

import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {

    public static int getIntervalMonths(String startDate, String endDate) {
        startDate = startDate.replaceAll("-", "");
        StringBuffer sb = new StringBuffer(startDate);
        sb.insert(4, "-");
        startDate = startDate.length() == 6 ? sb.append("-01").toString() : sb.insert(7, "-").toString();
        endDate = endDate.replaceAll("-", "");
        StringBuffer sb1 = new StringBuffer(endDate);
        sb1.insert(4, "-");
        endDate = endDate.length() == 6 ? sb1.append("-01").toString() : sb1.insert(7, "-").toString();

        Date st = parseStringToUtilDate(startDate);
        Date et = parseStringToUtilDate(endDate);

        String sy = getYear(st);//from ww  w  .  j av  a 2  s .c o  m
        String ey = getYear(et);

        int MonthByYear = 0;
        int reVal = Integer.valueOf(getMonth(et)).intValue() - Integer.valueOf(getMonth(st)).intValue();

        if (!sy.equals("ey")) {
            MonthByYear = (Integer.valueOf(ey).intValue() - Integer.valueOf(sy).intValue()) * 12;
        }
        return MonthByYear + reVal;
    }

    public static java.util.Date parseStringToUtilDate(String strDate) {

        java.util.Date date = null;
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            date = df.parse(strDate);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return date;
    }

    public static String getYear(Date date) {
        if (null == date) {
            return null;
        }
        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
        return yearFormat.format(date);
    }

    public static String getMonth(Date date) {
        if (null == date) {
            return null;
        }
        SimpleDateFormat yearFormat = new SimpleDateFormat("MM");
        return yearFormat.format(date);
    }
}

Related

  1. getBeforeOrAfterDate(String strDate, int months)
  2. getCurMonth2Long()
  3. getCurrMonthLastDay()
  4. getEndDateOfMonth(String yyyymmdd)
  5. getEngMonth()
  6. getIntevalMonth(String strDate1, String strDate2)
  7. getMonth()
  8. getMonth()
  9. getMonth()