Java GregorianCalendar - roll() Method
The java.util.GregorianCalendar.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 GregorianCalendar 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 field. |
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 the specified 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, 10, 30); //printing the Calendar System.out.println("The Calendar is: " + Cal.getTime()); //rolling the month up by 2 Cal.roll(GregorianCalendar.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 - GregorianCalendar