Java Utility Library

Java Calendar - roll() Method



The java.util.Calendar.roll() method is used to add a signed amount to the specified calendar field without changing larger fields. A negative roll amount means to subtract from field without changing larger fields. If the specified amount is 0, this method performs nothing.

Example: Consider a Calendar originally set to November 30, 1999. Calling roll(Calendar.MONTH, 2) sets the calendar to January 30, 1999. The YEAR field is unchanged because it is a larger field than MONTH.

Syntax

public void roll(int field, int amount)

Parameters

field Specify the time field.
amount Specify the signed amount to add to the calendar field.

Return Value

void type.

Exception

NA.

Example:

In the example below, the java.util.Calendar.roll() method is used to add the specified unit of time on the given time field of the Calendar object.

import java.util.*;

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

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

    //rolling the month up by 2
    Cal.roll(Calendar.MONTH, 2);

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

The output of the above code will be:

The Calendar is: Mon Nov 30 00:00:00 UTC 2015
Modified Calendar is: Fri Jan 30 00:00:00 UTC 2015

❮ Java.util - Calendar