Java Calendar Different getDifference(int field, Calendar aCalX, Calendar aCalY)

Here you can find the source of getDifference(int field, Calendar aCalX, Calendar aCalY)

Description

get Difference

License

Open Source License

Declaration

public static final int getDifference(int field, Calendar aCalX, Calendar aCalY) 

Method Source Code

//package com.java2s;

import java.util.Calendar;

import java.util.GregorianCalendar;

public class Main {
    public static final int getDifference(int field, Calendar aCalX, Calendar aCalY) {
        int gap = 0;
        int step = 0;
        Calendar calX = new GregorianCalendar();
        Calendar calY = new GregorianCalendar();

        calX.set(aCalX.get(Calendar.YEAR), aCalX.get(Calendar.MONTH), aCalX.get(Calendar.DATE), 0, 0, 0);
        calY.set(aCalY.get(Calendar.YEAR), aCalY.get(Calendar.MONTH), aCalY.get(Calendar.DATE), 0, 0, 0);

        step = (calX.before(calY) ? -1 : 1);

        if (field == Calendar.DATE) {
            while (!calX.equals(calY)) {
                calY.add(Calendar.DATE, step);
                gap = gap + step;//  w w  w.  j av a2s. com
            }
        } else if (field == Calendar.MONTH) {
            calX.set(calX.get(Calendar.YEAR), calX.get(Calendar.MONTH), 1);
            calY.set(calY.get(Calendar.YEAR), calY.get(Calendar.MONTH), 1);
            while (!calX.equals(calY)) {
                calY.add(Calendar.MONTH, step);
                gap = gap + step;
            }
        } else if (field == Calendar.YEAR) {
            calX.set(calX.get(Calendar.YEAR), 1, 1);
            calY.set(calY.get(Calendar.YEAR), 1, 1);
            while (!calX.equals(calY)) {
                calY.add(Calendar.YEAR, step);
                gap = gap + step;
            }
        }

        return gap;
    }
}

Related

  1. getDateDiff(Calendar c1, Calendar c2)
  2. getDateDiff(Calendar d1, Calendar d2)
  3. getDateDiff(Date d1, Date d2, int gregorianCalendarUnits)
  4. getDaysDifference(Calendar refDate, Date date)
  5. getDifference(int constant, Calendar first, Calendar second)
  6. getDifferenceInDays(Calendar fromDate, Calendar toDate)
  7. getDifferenceInSeconds(Calendar calendarStart, Calendar calendarEnd)
  8. getDiffPartialYears(Date date, GregorianCalendar b)
  9. getDiffTargetDate(Calendar cal, int diffDay)