Find the number of units passed between two Calendar objects. - Java java.util

Java examples for java.util:Calendar Calculation

Description

Find the number of units passed between two Calendar objects.

Demo Code


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main{
    /**//from  ww  w. j a  v a2 s  .  co m
     * Find the number of units passed between two {@link Calendar} objects.
     * 
     * @param c1
     *            The first occurring {@link Calendar}
     * 
     * @param c2
     *            The later occurring {@link Calendar}
     * 
     * @param unit
     *            The unit to calculate the difference in
     * 
     * @return the number of units passed
     */
    public static long difference(Calendar c1, Calendar c2, Unit unit) {

        Calendar first = (Calendar) c1.clone();
        Calendar last = (Calendar) c2.clone();

        long difference = c2.getTimeInMillis() - c1.getTimeInMillis();

        long increment = (long) Math.floor((double) difference
                / (double) unit.estimate);
        increment = Math.max(increment, 1);

        long total = 0;

        while (increment > 0) {
            add(first, unit.calendarUnit, increment);
            if (first.after(last)) {
                add(first, unit.calendarUnit, increment * -1);
                increment = (long) Math.floor(increment / 2);
            } else {
                total += increment;
            }
        }

        return total;
    }
    /**
     * Find the number of units passed between two {@link Date} objects.
     * 
     * @param d1
     *            The first occurring {@link Date}
     * 
     * @param d2
     *            The later occurring {@link Date}
     * 
     * @param unit
     *            The unit to calculate the difference in
     * 
     * @return the number of units passed
     */
    public static long difference(Date d1, Date d2, Unit unit) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(d1);

        Calendar c2 = Calendar.getInstance();
        c2.setTime(d2);

        return difference(c1, c2, unit);
    }
    /**
     * Add a long amount to a calendar. Similar to calendar.add() but accepts a
     * long argument instead of limiting it to an int.
     * 
     * @param c
     *            the calendar
     * 
     * @param unit
     *            the unit to increment
     * 
     * @param increment
     *            the amount to increment
     */
    public static void add(Calendar c, int unit, long increment) {
        while (increment > Integer.MAX_VALUE) {
            c.add(unit, Integer.MAX_VALUE);
            increment -= Integer.MAX_VALUE;
        }
        c.add(unit, (int) increment);
    }
}

Related Tutorials