Get the difference in time between two calendars for an individual time unit. - Java java.util

Java examples for java.util:Time

Description

Get the difference in time between two calendars for an individual time unit.

Demo Code

/*//from   w w  w .j av  a 2 s  . co m
 * This document is a part of the source code and related artifacts for StilesLib, an open source library that
 * provides a set of commonly-used functions for Bukkit plugins.
 *
 * http://github.com/mstiles92/StilesLib
 *
 * Copyright (c) 2014 Matthew Stiles (mstiles92)
 *
 * Licensed under the Common Development and Distribution License Version 1.0
 * You may not use this file except in compliance with this License.
 *
 * You may obtain a copy of the CDDL-1.0 License at http://opensource.org/licenses/CDDL-1.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the license.
 */
//package com.java2s;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class Main {
    public static void main(String[] argv) throws Exception {
        int constant = 2;
        Calendar first = Calendar.getInstance();
        Calendar second = Calendar.getInstance();
        System.out.println(getDifference(constant, first, second));
    }

    /**
     * Get the difference in time between two calendars for an individual time unit.
     *
     * @param constant the constant representing the time unit to compare
     * @param first the first Calendar object
     * @param second the second Calendar object
     * @return the number of the specified time units between the first and second Calendar objects
     */
    private static int getDifference(int constant, Calendar first,
            Calendar second) {
        int difference = 0;
        Calendar temp = new GregorianCalendar();
        temp.setTimeInMillis(first.getTimeInMillis());

        while (!temp.after(second)) {
            temp.add(constant, 1);
            difference += 1;
        }

        return difference - 1;
    }
}

Related Tutorials