Java examples for java.util:Year
Retrieve the amount of elapsed years 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(elapsedYears(before, after)); }//from w w w . j ava2 s . co m /** * Retrieve the amount of elapsed years 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 years between the two given calendars. */ public static int elapsedYears(Calendar before, Calendar after) { return elapsed(before, after, Calendar.YEAR); } /** * 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."); } } }