for certain calendars, but no calendar class is required to use such constants. In particular, the month names in
Calendar (such as Calendar.JUNE) are names for the various month numbers (such as 5month numbers
start at 0 ), with a special month UNDECIMBER for the thirteenth month that many calendars have. But no
calendar is required to use these constants.
Each Calendar object represents a particular moment in time on that calendar. The Calendar class
provides only constructors that create an object for the current time, either in the default locale and time zone
or in specified ones.
Calendar objects represent a moment in time, but they are not responsible for displaying the date. That
locale-sensitive procedure is the job of the DateFormat class, which will soon be described.
You can obtain a calendar object for a locale by invoking one of the static Calendar.getInstance
methods. With no arguments, getInstance returns an object of the best available calendar type (currently
only GregorianCalendar) for the default locale and time zone, set to the current time. The other
overloads allow you to specify the locale, the time zone, or both. The static getAvailableLocales
method returns an array of Locale objects for which calendars are installed on the system.
With a calendar object in hand, you can manipulate the date. The following example prints the next week of
days for a given calendar object:
public static void oneWeek(PrintStream out, Calendar cal) {
Calendar cur = (Calendar) cal.clone(); //modifiable copy
int dow = cal.get(Calendar.DAY_OF_WEEK);
do {
out.println(cur.getTime());
cur.add(Calendar.DAY_OF_WEEK, 1);
} while (cur.get(Calendar.DAY_OF_WEEK) != dow);
}
First we make a copy of the calendar argument so that we can make changes without affecting the calendar we
were passed.[1] Instead of assuming that there are seven days in a week (who knows what kind of calendar we
were given?), we loop, printing the time and adding one day to that time, until we have printed a week's worth
of days. We detect whether a week has passed by looking for the next day whose "day of the week" is the
same as that of the original object.
[1] For historical reasons Calendar.clone returns Object not Calendar, so a cast is
required.
The Calendar class defines many kinds of calendar fields for calendar objects, such as DAY_OF_WEEK in
the preceding code. These calendar fields are constants used in the methods that manipulate parts of the time: