Java Utility Library

Java GregorianCalendar - roll() Method



The java.util.GregorianCalendar.roll() method is used to add or subtract (up/down) a single unit of time on the given time field without changing larger fields.

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

Syntax

public void roll(int field, boolean up)

Parameters

field Specify the time field.
up Indicates if the value of the specified calendar field is to be rolled up or rolled down. Use true if rolling up, false otherwise.

Return Value

void type.

Exception

Throws IllegalArgumentException, if field is ZONE_OFFSET, DST_OFFSET, or unknown, or if any calendar fields have out-of-range values in non-lenient mode.

Example:

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

import java.util.*;

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

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

    //rolling the month up by 1
    Cal.roll(GregorianCalendar.MONTH, true);

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

The output of the above code will be:

The Calendar is: Fri Dec 25 00:00:00 UTC 2015
Modified Calendar is: Sun Jan 25 00:00:00 UTC 2015

❮ Java.util - GregorianCalendar