Java Reference
In-Depth Information
// day will contain day of month of the current date
int day = gc.get(Calendar.DAY_OF_MONTH);
// hour will contain hour value
int hour = gc.get(Calendar.HOUR);
// minute will contain minute value
int minute = gc.get(Calendar.MINUTE);
// second will contain second values
int second = gc.get(Calendar.SECOND);
You can set the date interpretation to be lenient or not lenient by using the setLenient() method of the
GregorianCalendar class. By default, it is lenient. If the date interpretation is lenient, a date such as March 35, 2003
is interpreted as April 5, 2003. If date interpretation is not lenient, such a date will result in an error. You can also
compare two dates, whether one date occurs before or after another, by using before() and after() methods. There
are two methods, add() and roll() , which need explanation. They are described below.
The add( ) Method
The add() method is used to add an amount to a particular field in a date. The amount being added may be negative
or positive. Suppose you have the date of December 1, 2003 stored in a GregorianCalendar object. You want to add
5 to the month field. The value for the month field will be 16, which is out of range (0 - 11). In such a case, the larger
date field (here, year is larger than month) will be adjusted to accommodate the overflow. The date, after adding 5 to
the month field, will be May 1, 2004. The following snippet of code illustrates this concept:
GregorianCalendar gc = new GregorianCalendar(2003, Calendar.DECEMBER, 1);
gc.add(Calendar.MONTH, 5); // Now gc represents May 1, 2004
This method may result in adjusting smaller fields, too. Suppose you have the date of January 30, 2003 stored
in a GregorianCalendar object. You add 1 to the month field. The new month field does not overflow. However, the
resulting date, February 30, 2003, is not a valid date. The day of month must be between 1 and 28 in the month of
February 2003. In this case, the day of month field is automatically adjusted. It is set to the nearest possible valid value,
which is 28 . The resulting date will be February 28, 2003.
The roll( ) Method
The roll() method works the same as the add() method, except it does not change the larger field when the field
being changed overflows. It may adjust the smaller fields to make the date a valid date. It is an overloaded method.
void roll(int field, int amount)
void roll(int field, boolean up)
The second version rolls up/down the specified field by a single unit of time, whereas the first version rolls the
specified field by the specified amount . Therefore, gc.roll(Calendar.MONTH, 1) is the same as gc.roll(Calendar.
MONTH, true) and gc.roll(Calendar.MONTH, -1) is the same as gc.roll(Calendar.MONTH, false) . Listing 12-28
illustrates the use of some of the methods of the GregorianCalendar class. You may get a different output.
 
Search WWH ::




Custom Search