Java Calendar Different dateDiff(int type, Calendar fromDate, Calendar toDate)

Here you can find the source of dateDiff(int type, Calendar fromDate, Calendar toDate)

Description

Get the difference of a specific calendar field for 2 calendar instances.

License

Open Source License

Parameter

Parameter Description
type The calendar field type, see Calendar documentation.
fromDate The calendar to check from.
toDate The calendar to check against.

Return

The field difference.

Declaration

static int dateDiff(int type, Calendar fromDate, Calendar toDate) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Calendar;

public class Main {
    /**//from   w ww  .  j  a  va  2 s. com
     * Get the difference of a specific calendar field for 2 calendar instances.
     * 
     * @param type The calendar field type, see {@link Calendar} documentation.
     * @param fromDate The calendar to check from.
     * @param toDate The calendar to check against.
     * @return The field difference.
     */
    static int dateDiff(int type, Calendar fromDate, Calendar toDate) {
        boolean future = toDate.after(fromDate);

        int diff = 0;
        long savedDate = fromDate.getTimeInMillis();
        while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate))) {
            savedDate = fromDate.getTimeInMillis();
            fromDate.add(type, future ? 1 : -1);
            diff++;
        }
        diff--;
        fromDate.setTimeInMillis(savedDate);
        return diff;
    }
}

Related

  1. countDiffDay(Calendar c1, Calendar c2)
  2. countDiffMonth(Calendar cBegin, Calendar cEnd, boolean isRoundUp)
  3. datediff(Calendar c1, Calendar c2)
  4. dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future)
  5. dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future)
  6. dateDiff(long dateUtilitiesUnitField, Calendar firstDate, Calendar secondDate)
  7. dateDifferenceInMin(Calendar startDate, Calendar stopDate)