Calendar roll() Method in Java with Examples
Last Updated :
18 Nov, 2019
The roll(int calndr_field, boolean up_down) method in Calendar class is used to operate on the passed calendar field by moving the passed field, up or down by a single unit of time. This involves addition or subtraction of the time field without changing the larger fields.
Syntax:
public abstract void roll(int calndr_field, boolean up_down)
Parameters: The method takes two parameters:
- calndr_field: This is of Calendar type and refers to the field of the calendar that is to be operated upon.
- up_down: This is of the boolean type that is used to indicate whether to move calndr_field up or down or to increase or decrease. The true indicates adding a unit of time and false subtracts the same.
Return Value: The method does not return any value.
Below programs illustrate the working of roll() Method of Calendar class:
Example 1:
import java.util.*;
public class Calendar_Demo {
public static void main(String args[])
{
Calendar calndr = Calendar.getInstance();
System.out.println( "The Current Year"
+ " is: "
+ calndr.get(
Calendar.YEAR));
calndr.roll(Calendar.YEAR, false );
System.out.println( "The New Year is: "
+ calndr.get(
Calendar.YEAR));
calndr.roll(Calendar.YEAR, true );
System.out.println( "The new year is: "
+ calndr.get(
Calendar.YEAR));
}
}
|
Output:
The Current Year is: 2019
The New Year is: 2018
The new year is: 2019
Example 2:
import java.util.*;
public class Calendar_Demo {
public static void main(String args[])
{
Calendar calndr = Calendar.getInstance();
System.out.println( "The Current Month"
+ " is: "
+ calndr.get(
Calendar.MONTH));
calndr.roll(Calendar.MONTH, true );
System.out.println( "The New Month is: "
+ calndr.get(
Calendar.MONTH));
calndr.roll(Calendar.MONTH, false );
System.out.println( "The new month is: "
+ calndr.get(
Calendar.MONTH));
}
}
|
Output:
The Current Month is: 1
The New Month is: 2
The new month is: 1
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#roll-int-boolean-
Share your thoughts in the comments
Please Login to comment...