Java Reference
In-Depth Information
Getting Date and Time Information
You can get information such as the day, the month, and the year from a GregorianCalendar object by us-
ing the get() method and specifying what you want by the argument. The possible arguments to the get()
method are those defined in the earlier table of constants 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 constants defined in the class:
if(day == calendar.SATURDAY)
// Go to game...
Because 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.TUESDAY:
// 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() meth-
od. 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 mod-
ifies 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 the
following:
calendar.roll(calendar.MONTH, false); // Go back a month
The change can affect other fields. If the original month were January, rolling it back by one would make
the date December of the previous year.
Another version of the roll() method allows you to roll a field by a specified signed integer amount as
the second argument. A negative value rolls down and a positive value rolls up.
Search WWH ::




Custom Search