Java examples for java.util:Calendar Calculation
Retrieve the amount of elapsed days between the two given calendars.
//package com.java2s; import java.util.Calendar; public class Main { public static void main(String[] argv) throws Exception { Calendar before = Calendar.getInstance(); Calendar after = Calendar.getInstance(); System.out.println(elapsedDays(before, after)); }//w w w .j a va2 s.c o m /** * Retrieve the amount of elapsed days between the two given calendars. * * @param before The first calendar with expected date before the second * calendar. * @param after The second calendar with expected date after the first * calendar. * @return The amount of elapsed days between the two given calendars. */ public static int elapsedDays(Calendar before, Calendar after) { return elapsed(before, after, Calendar.DATE); } /** * Retrieve the amount of elapsed time between the two given calendars based * on the given calendar field as defined in the Calendar constants, e.g. * <tt>Calendar.MONTH</tt>. * * @param before The first calendar with expected date before the second * calendar. * @param after The second calendar with expected date after the first * calendar. * @param field The calendar field as defined in the Calendar constants. * @return The amount of elapsed time between the two given calendars based * on the given calendar field. */ private static int elapsed(Calendar before, Calendar after, int field) { checkBeforeAfter(before, after); Calendar clone = (Calendar) before.clone(); // Otherwise changes are // been reflected. int elapsed = -1; while (!clone.after(after)) { clone.add(field, 1); elapsed++; } return elapsed; } /** * Check if the first calendar is actually dated before the second calendar. * * @param before The first calendar with expected date before the second * calendar. * @param after The second calendar with expected date after the first * calendar. */ private static void checkBeforeAfter(Calendar before, Calendar after) { if (before.after(after)) { throw new IllegalArgumentException( "The first calendar should be dated before the second calendar."); } } }