Java Calendar - roll() Method
The java.util.Calendar.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 Calendar 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 abstract 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
NA.
Example:
In the example below, the java.util.Calendar.roll() method is used to add a single 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, 11, 25); //printing the Calendar System.out.println("The Calendar is: " + Cal.getTime()); //rolling the month up by 1 Cal.roll(Calendar.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 - Calendar