Java Month Convert differenceMonth(String strDate1, String strDate2)

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

Description

difference Month

License

Open Source License

Declaration

public static int differenceMonth(String strDate1, String strDate2) throws ParseException 

Method Source Code


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

import java.text.DateFormat;
import java.text.ParseException;

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

public class Main {

    public static int differenceMonth(String strDate1, String strDate2) throws ParseException {
        Date date1 = DateFormat.getDateInstance().parse(strDate1);
        Date date2 = DateFormat.getDateInstance().parse(strDate2);
        return differenceMonth(date1, date2);
    }/*from  w ww.j a  va  2 s.  co m*/

    public static int differenceMonth(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        cal1.set(Calendar.DATE, 1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        cal2.set(Calendar.DATE, 1);
        int count = 0;
        if (cal1.before(cal2)) {
            while (cal1.before(cal2)) {
                cal1.add(Calendar.MONTH, 1);
                count--;
            }
        } else {
            count--;
            while (!cal1.before(cal2)) {
                cal1.add(Calendar.MONTH, -1);
                count++;
            }
        }
        return count;
    }

    public static Calendar add(Calendar cal, int addYera, int addMonth, int addDate, int addHour, int addMinute,
            int addSecond, int addMillisecond) {
        if (cal == null) {
            cal = Calendar.getInstance();
        }
        cal.add(Calendar.YEAR, addYera);
        cal.add(Calendar.MONTH, addMonth);
        cal.add(Calendar.DATE, addDate);
        cal.add(Calendar.HOUR_OF_DAY, addHour);
        cal.add(Calendar.MINUTE, addMinute);
        cal.add(Calendar.SECOND, addSecond);
        cal.add(Calendar.MILLISECOND, addMillisecond);
        return cal;
    }
}

Related

  1. ConvertNumToMonth(int mesEntrada)
  2. convertToAlphaMonth(final int importIntMonth)
  3. convertToMonth_long(int month)
  4. convertToNumericMonth(String importStrMonth)
  5. createFutureDate(int days, int months)
  6. isCurMonth(String month)
  7. month()
  8. month(Date date, Locale locale)
  9. month2String(Date date)