THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

month has more than 31 days.


The set method allows you to specify a date by certain calendar fields and then calculate the time associated
with that date. For example, you can calculate on which day of the week a particular date falls:


public static int dotw(int year, int month, int date) {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DATE, date);
return cal.get(Calendar.DAY_OF_WEEK);
}


The method dotw calculates the day of the week on the Gregorian calendar for the given date. It creates a
Gregorian calendar object, sets the date fields for year, month, and day, and returns the resulting day of the
week.


The clear method can be used to reset a field's value to be unspecified. You can use clear with no
parameters to clear all calendar fields. The isSet method returns true if a field currently has a value set.


Three variants of set change particular fields you commonly need to manipulate, leaving unspecified fields
alone:


public void set(int year, int month, int date)
public void set(int year, int month, int date, int hrs, int min)
public void set(int year, int month, int date, int hrs, int min, int sec)


You can also use setTime to set the calendar's time from a Date object.


A calendar field that is out of range can be interpreted correctly. For example, January 32 can be equivalent to
February 1. Whether it is treated as such or as an error depends on whether the calendar is considered to be
lenient. A lenient calendar will do its best to interpret values as valid. A strict (non-lenient) calendar will not
accept any values out of range, throwing IllegalArgumentException. The setLenient method
takes a boolean that specifies whether parsing should be lenient; isLenient returns the current setting.


A week can start on any day, depending on the calendar. You can discover the first day of the week with the
method getFirstDayOfWeek. In a Gregorian calendar for the United States this method would return
SUNDAY, whereas Ireland uses MONDAY. You can change this by invoking setFirstDayOfWeek with a
valid weekday index.


Some calendars require a minimum number of days in the first week of the year. The method
getMinimalDaysInFirstWeek returns that number; the method setMinimalDaysInFirstWeek
lets you change it. The minimum number of days in a week is important when you are trying to determine in
which week a particular date fallsfor example, in some calendars, if January 1 is a Friday it may be considered
part of the last week of the preceding year.


You can compare two Calendar objects by using compareTo since Calendar implements
Comparable. If you prefer, you can use the before and after methods to compare the objects.

Free download pdf