Java Reference
In-Depth Information
ject 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 respons-
ible 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
Gregori-
anCalendar
) 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 fol-
lowing 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
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 de-
tect 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.