How to use the Calendar and GregorianCalendar fields and methods.

The associated package:

  • java.util.Calendar

Common fields of the Calendar class:

DATE DAY_OF_MONTH DAY_OF_WEEK DAY_OF_YEAR
HOUR HOUR_OF_DAY MINUTE MONTH
SECONDS YEAR MONDAY…SUNDAY JANUARY…DECEMBER

Common methods of the Calendar and GregorianCalendar classes:

Method Description
set(intYear, intMonth, . . .) Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH
set(intField, intValue) Sets the given calendar field to the given value
setTime(Date) Sets this Calendar's time with the given Date
add(intField, intValue) Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.
roll(intField, intValue) Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
roll(intField, booleanValue) Adds the specified (signed) amount to the specified calendar field without changing larger fields.
get(intField) Returns the value of the given calendar field
getTime() Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Example 1: Code that changes a GregorianCalendar object:

GregorianCalendar endDate = newGregorianCalendar(2005,0,1);
endDate.set(2005,2,30);
endDate.add(Calendar.MONTH, 5);
endDate.roll(Calendar.MONTH, 5);

Example 2: Code that accesses fields in a GregorianCalendar object:

GregorianCalendar birthDay = newGregorianCalendar(2005, Calendar.FEBRUARY, 4);
int month = birthDay.get(Calendare.MONTH); // Returns 1

More information can be found here:

http://www.j2ee.me/javase/6/docs/api/java/util/Calendar.html