Retrieve the amount of elapsed time between the two given calendars based on the given calendar field as defined in the Calendar constants, e.g. - Java java.util

Java examples for java.util:Calendar Calculation

Description

Retrieve the amount of elapsed time between the two given calendars based on the given calendar field as defined in the Calendar constants, e.g.

Demo Code


//package com.java2s;
import java.util.Calendar;

public class Main {
    public static void main(String[] argv) throws Exception {
        Calendar before = Calendar.getInstance();
        Calendar after = Calendar.getInstance();
        int field = 2;
        System.out.println(elapsed(before, after, field));
    }//from   w w  w  .j  a  v a  2s.  c  o  m

    /**
     * Retrieve the amount of elapsed time between the two given calendars based
     * on the given calendar field as defined in the Calendar constants, e.g.
     * <tt>Calendar.MONTH</tt>.
     *
     * @param before The first calendar with expected date before the second
     * calendar.
     * @param after The second calendar with expected date after the first
     * calendar.
     * @param field The calendar field as defined in the Calendar constants.
     * @return The amount of elapsed time between the two given calendars based
     * on the given calendar field.
     */
    private static int elapsed(Calendar before, Calendar after, int field) {
        checkBeforeAfter(before, after);
        Calendar clone = (Calendar) before.clone(); // Otherwise changes are
        // been reflected.
        int elapsed = -1;
        while (!clone.after(after)) {
            clone.add(field, 1);
            elapsed++;
        }
        return elapsed;
    }

    /**
     * Check if the first calendar is actually dated before the second calendar.
     *
     * @param before The first calendar with expected date before the second
     * calendar.
     * @param after The second calendar with expected date after the first
     * calendar.
     */
    private static void checkBeforeAfter(Calendar before, Calendar after) {
        if (before.after(after)) {
            throw new IllegalArgumentException(
                    "The first calendar should be dated before the second calendar.");
        }
    }
}

Related Tutorials