Java Reference
In-Depth Information
calendar.set(Calendar.DAY
_
OF
_
WEEK, Calendar.TUESDAY);
Of course, since a variable of type
GregorianCalendar
also has all these constants you could use the
variable name,
calendar
, instead of the class name as the qualifier for the name of the constants here.
Getting Date and Time Information
You can get information such as the day, the month, and the year from a
GregorianCalendar
object
by using the
get()
method and specifying what you want as an argument. The possible arguments to
the
get()
method are those defined in the table of constants above identifying calendar fields. All
values returned are of type
int
. For example, you could get the day of the week with the statement:
int day = calendar.get(calendar.DAY
_
OF
_
WEEK);
You could now test this for a particular day using the constant defined in the class:
if(day == calendar.SATURDAY)
// Go to game...
Since the values for
day
are integers, you could equally well use a
switch
statement:
switch(day) {
case Calendar.MONDAY:
// do the washing...
break;
case Calendar.MONDAY:
// do something else...
break;
// etc...
}
Modifying Dates and Times
Of course, you might want to alter the current instant in the calendar, and for this you have the
add()
method. The first argument determines what units you are adding in, and you specify this argument using the
same field designators as in the previous list. For example, you can add 14 to the year with the statement:
calendar.add(calendar.YEAR, 14); // 14 years into the future
To go into the past, you just make the second argument negative:
calendar.add(calendar.MONTH, -6); // Go back 6 months
You can increment or decrement a field of a calendar by 1 using the
roll()
method. This method
modifies the field specified by the first argument by +1 or -1, depending on whether the second
argument is
true
or
false
. For example, to decrement the current month in the object
calendar
,
you would write: