How to Create a Calendar in Java (4 Steps)

By David Weinberg

i Stockbyte/Stockbyte/Getty Images

Java's calendar class stores information about a moment in time. The class can be used to compare with different times, to manipulate information about one time or to ascertain the current time. Creating and manipulating the calendar class is relatively straightforward. The programmer needs to import only one file from the java.util package. A calendar object can be local or global within a program and is easily initialized to the current time.

Step 1

Type "import java.util.Calendar" at the top of the java file, outside of the class declaration, in which you will be creating a calendar to import the Calendar class into your program.

Step 2

Type "Calendar cal = Calendar.getInstance();" into your program wherever you need a calendar object in order to create a new calendar named cal with the current date and time. Change "cal" to another variable name when creating more than one calendar object.

Step 3

Use the calendar object's set(int Field, int Value) method to set the time you want your calendar object to represent. Use the constants in the Calendar class to define field and value. For example, typing "cal.set(Calendar.MONTH, Calendar.MAY);" will set the calendar's month to May. Typing "cal.set(Calendar.YEAR, 1988);" will set the calendar's year to 1988.

Step 4

Use the calendar object's get(int Field) method to return the value stored in a given field. Once again, use the constants in the Calendar class to define the field. For example, "int i = cal.get(Calendar.YEAR)" will assign the value 1988 to the variable i.