roll(int boolean): This method is available in java.util.GregorianCalendar class of Java.
Syntax:
void java.util.GregorianCalendar.roll(int field, boolean up)
This method takes two arguments one of type int and the other of type boolean as its parameter. This method adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
Parameters: Two parameters are required for this method.
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.
field: the time field.
Throws:
IllegalArgumentException - if the field is ZONE_OFFSET, DST_OFFSET, or unknown, or if any calendar fields have out-of-range values in non-lenient mode.
Approach 1: When no exception
Java
import java.util.GregorianCalendar;public class GregorianCalendarroll {public static void main(String[] args) {GregorianCalendar cal = new GregorianCalendar();int field = GregorianCalendar.AD;boolean up = false;cal.roll(field, up);System.out.println(cal);}}
Output:
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2021,MONTH=1,WEEK_OF_YEAR=8,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=47,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=35,SECOND=22,MILLISECOND=161,ZONE_OFFSET=19800000,DST_OFFSET=0]
Approach 2: IllegalArgumentException
Java
import java.util.GregorianCalendar;public class GregorianCalendarroll {public static void main(String[] args) {GregorianCalendar cal = new GregorianCalendar();int field = GregorianCalendar.ZONE_OFFSET;boolean up = false;cal.roll(field, up);System.out.println(cal);}}
Output:
Exception in thread "main" java.lang.IllegalArgumentException at java.base/java.util.GregorianCalendar.roll(GregorianCalendar.java:1168) at java.base/java.util.GregorianCalendar.roll(GregorianCalendar.java:1112)
No comments:
Post a Comment