compare Weeks between two date value in Calendar - Android java.util

Android examples for java.util:Week

Description

compare Weeks between two date value in Calendar

Demo Code

import android.annotation.SuppressLint;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main{
    /**/*  w  w w.  java  2s.  com*/
     * @param p_cal1
     * @param p_cal2
     * @return p_cal1 - p_cal2 in weeks, <code>null</code> if one of them is null
     */
    public static Integer differnceBetweenWeeks(Calendar p_cal1,
            Calendar p_cal2) {
        if (p_cal1 == null || p_cal2 == null) {
            return null;
        }
        Calendar cal1 = (Calendar) p_cal1.clone();
        Calendar cal2 = (Calendar) p_cal1.clone();
        cal2.set(Calendar.YEAR, p_cal2.get(Calendar.YEAR));
        cal2.set(Calendar.MONTH, p_cal2.get(Calendar.MONTH));
        cal2.set(Calendar.WEEK_OF_MONTH, p_cal2.get(Calendar.WEEK_OF_MONTH));
        int counter = 0;
        int adder = compareWeeks(cal1, cal2);
        while (adder != 0) {
            counter += adder;
            cal2.add(Calendar.WEEK_OF_MONTH, adder);
            adder = compareWeeks(cal1, cal2);
        }

        return counter;
    }
    /**
     * @param p_cal1
     * @param p_cal2
     * @return -1 or 1
     */
    private static int compareWeeks(Calendar p_cal1, Calendar p_cal2) {
        int a[] = { Calendar.YEAR, Calendar.MONTH, Calendar.WEEK_OF_MONTH };
        int difference = 0;
        for (int i = 0; i < a.length; i++) {
            difference = p_cal1.get(a[i]) - p_cal2.get(a[i]);
            if (difference != 0) {
                break;
            }
        }
        int retVal = 0;
        if (difference != 0) {
            retVal = difference / Math.abs(difference);
        }
        return retVal;
    }

}

Related Tutorials