Java Utility Library

Java Calendar - set() Method



The java.util.Calendar.set() method is used to set the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, MINUTE, and SECOND. Previous values of other fields are retained.

Syntax

public final void set(int year,
                      int month,
                      int date,
                      int hourOfDay,
                      int minute,
                      int second)

Parameters

year Specify the value used to set the YEAR calendar field.
month Specify the value used to set the MONTH calendar field. Month value is 0-based.
date Specify the value used to set the DAY_OF_MONTH calendar field.
hourOfDay Specify the value used to set the HOUR_OF_DAY calendar field.
minute Specify the value used to set the MINUTE calendar field.
second Specify the value used to set the SECOND calendar field.

Return Value

void type.

Exception

NA.

Example:

In the example below, the java.util.Calendar.set() method is used to set the given Calendar to the specified date and time.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a Calendar instance
    Calendar Cal = Calendar.getInstance();

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

    //setting the calendar to 00:00:00 hrs of 1 March 2016
    Cal.set(2016, 2, 1, 0, 0, 0);

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

The output of the above code will be:

The Calendar is: Sat May 08 10:34:33 UTC 2021
New Calendar is: Tue Mar 01 00:00:00 UTC 2016

❮ Java.util - Calendar