HOW-TO: Use the Calendar class in Java

Sometimes a program needs to know something about a date, like what day of the week it occured. Maybe you want to do something like know which months have 31 days in them. All of this can be done with the Calendar class in the java.util package.

First we need to import the package:
import java.util.Calendar;

Next we have to get an instance of the Calendar class:
Calendar cal = Calendar.getInstance();

Notice that we cannot directly invoke the constructor with new Calendar();, as it is an abstract class.

Next we have to set the date and time that we want to know stuff about:

For the month parameter, January is 0, February is 1, etc. You can also use the constants Calendar.MONTH.

Now we can do some really neat stuff with our calendar. Each calendar has a set of parameters that are automatically updated when the calendar is changed. These can be accessed with the get() method and a set of constants that define a number of accessible fields.

For instance, to find the week of the year that a day falls on:
int week = cal.get(Calendar.WEEK_OF_YEAR)

Another interesting method is getActualMaximum(). This allows you to find, for instance, the number of days in a particular month:
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

Some fields that may be useful:

  • DAY_OF_WEEK – Returns the day of the week that a day falls on, 1-7
  • DAY_OF_YEAR – Returns the number of days into the year that the date occurs
  • WEEK_OF_MONTH – Returns the week in the current month where the date occurs
  • DAY_OF_MONTH – Returns the current day of the month

More information is available from the Javadoc page on the Calendar class

Next time I will cover some of the time aspects of the Calendar class.

Leave a Reply