Java examples for java.util:Calendar Calculation
Gets the calendar field of the given calendar by amount.
/*// ww w . java 2s.c om * $Id: CalendarUtils.java 3916 2011-01-12 10:21:58Z kleopatra $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ //package com.java2s; import java.util.Calendar; public class Main { public static void main(String[] argv) throws Exception { Calendar calendar = Calendar.getInstance(); int field = 2; System.out.println(get(calendar, field)); } public static final int DECADE = 5467; public static final int YEAR_IN_DECADE = DECADE + 1; /** * Gets the calendar field of the given calendar by amount. * * @param calendar * @param field the field to get, allowed are all fields known to * Calendar plus DECADE. * * @throws IllegalArgumentException */ public static int get(Calendar calendar, int field) { if (isNativeField(field)) { return calendar.get(field); } switch (field) { case DECADE: return decade(calendar.get(Calendar.YEAR)); case YEAR_IN_DECADE: return calendar.get(Calendar.YEAR) % 10; default: throw new IllegalArgumentException("unsupported field: " + field); } } /** * @param calendarField * @return */ private static boolean isNativeField(int calendarField) { return calendarField < DECADE; } /** * @param year * @return */ private static int decade(int year) { return (year / 10) * 10; } }