Retrieve the amount of elapsed milliseconds between the two given calendars. - Java java.util

Java examples for java.util:Calendar Calculation

Description

Retrieve the amount of elapsed milliseconds between the two given calendars.

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();
        System.out.println(elapsedMillis(before, after));
    }/*from  w w  w .  j a  v  a  2  s .  co  m*/

    /**
     * Retrieve the amount of elapsed milliseconds between the two given
     * calendars.
     *
     * @param before The first calendar with expected date before the second
     * calendar.
     * @param after The second calendar with expected date after the first
     * calendar.
     * @return The amount of elapsed milliseconds between the two given
     * calendars.
     */
    public static long elapsedMillis(Calendar before, Calendar after) {
        return elapsedMillis(before, after, 1); // 1ms is apparently 1ms.
    }

    /**
     * Retrieve the amount of elapsed milliseconds between the two given
     * calendars and directly divide the outcome by the given factor. E.g.: if
     * the division factor is 1, then you will get the elapsed milliseconds
     * unchanged; if the division factor is 1000, then the elapsed milliseconds
     * will be divided by 1000, resulting in the amount of elapsed seconds.
     *
     * @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 factor The division factor which to divide the milliseconds with,
     * expected to be at least 1.
     * @return The amount of elapsed milliseconds between the two given
     * calendars, divided by the given factor.
     */
    private static long elapsedMillis(Calendar before, Calendar after,
            int factor) {
        checkBeforeAfter(before, after);
        if (factor < 1) {
            throw new IllegalArgumentException("Division factor '" + factor
                    + "' should not be less than 1.");
        }
        return (after.getTimeInMillis() - before.getTimeInMillis())
                / factor;
    }

    /**
     * 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