Java Calendar Different reduceAndCorrect(Calendar start, Calendar end, int field, int difference)

Here you can find the source of reduceAndCorrect(Calendar start, Calendar end, int field, int difference)

Description

Reduces by difference, then if it overshot, calculates the overshot amount and fixes and returns the amount to change by.

License

Apache License

Parameter

Parameter Description
start Start of period being formatted
end End of period being formatted
field Field to reduce, as per constants in java.util.Calendar
difference amount to reduce by

Return

int reduced value

Declaration

static int reduceAndCorrect(Calendar start, Calendar end, int field, int difference) 

Method Source Code


//package com.java2s;
/*/* ww w.j  a v  a 2s .c  o  m*/
 * Copyright 2002-2005 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.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.
 */

import java.util.Calendar;

public class Main {
    /**
     * Reduces by difference, then if it overshot, calculates the overshot amount and 
     * fixes and returns the amount to change by.
     *
     * @param start Start of period being formatted
     * @param end End of period being formatted
     * @param field Field to reduce, as per constants in {@link java.util.Calendar}
     * @param difference amount to reduce by
     * @return int reduced value
     */
    static int reduceAndCorrect(Calendar start, Calendar end, int field, int difference) {
        end.add(field, -1 * difference);
        int endValue = end.get(field);
        int startValue = start.get(field);
        if (endValue < startValue) {
            int newdiff = startValue - endValue;
            end.add(field, newdiff);
            return newdiff;
        } else {
            return 0;
        }
    }
}

Related

  1. getTimeDiffSecond(Calendar first, Calendar second)
  2. getWeekDifference(Calendar before, Calendar after)
  3. getYearDifference(GregorianCalendar fromCalendar, GregorianCalendar toCalendar)
  4. millisDiff(Calendar c1, Calendar c2)
  5. minutesDiff(Calendar c1, Calendar c2)
  6. timeDiff(Calendar c1, Calendar c2)