Java Utility Library

Java Calendar - set() Method



The java.util.Calendar.set() method is used to set the given calendar field to the given value.

Syntax

public void set(int field,
                int value)

Parameters

field Specify the given calendar field.
value Specify the value to be set for the given calendar field.

Return Value

void type.

Exception

Throws ArrayIndexOutOfBoundsException, if the specified field is out of range (field < 0 || field >= FIELD_COUNT). in non-lenient mode.

Example:

In the example below, the java.util.Calendar.set() method is used to set the given Calendar field to the given value.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a Calendar object with specified date
    Calendar Cal = new GregorianCalendar(2015, 1, 25);

    //printing the Calendar
    System.out.println("The Calendar is: " + Cal.getTime());

    //setting the calendar month to October
    Cal.set(Calendar.MONTH, 9);

    //printing the Calendar
    System.out.println("New Calendar is: " + Cal.getTime());

    //setting the calendar year to 2012
    Cal.set(Calendar.YEAR, 2012);

    //printing the Calendar
    System.out.println("New Calendar is: " + Cal.getTime());
  }
}

The output of the above code will be:

The Calendar is: Wed Feb 25 00:00:00 UTC 2015
New Calendar is: Sun Oct 25 00:00:00 UTC 2015
New Calendar is: Thu Oct 25 00:00:00 UTC 2012

❮ Java.util - Calendar