Java examples for java.util:Month
Retrieve the amount of elapsed months 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(elapsedMonths(before, after)); }// ww w . ja v a 2 s. c o m /** * Retrieve the amount of elapsed months 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 months between the two given calendars. */ public static int elapsedMonths(Calendar before, Calendar after) { return elapsed(before, after, Calendar.MONTH); } /** * 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."); } } }