GregorianCalendar roll(int, int) in Java

roll(int, int): This method is available in java.util.GregorianCalendar class of Java.

Syntax:

void java.util.GregorianCalendar.roll(int field, int amount)

This method takes two arguments of type int as its parameters. This method adds a signed amount to the specified calendar field without changing larger fields.

Parameters: Two parameters are required for this method.

field: the calendar field.

amount: the signed amount to add to the 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 GregorianCalendarroll2 {
    public static void main(String[] args) {

        GregorianCalendar cal = new GregorianCalendar();

        int field = GregorianCalendar.BC, amount = 10;
        cal.roll(field, amount);
        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=2022,MONTH=1,WEEK_OF_YEAR=8,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=49,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=43,SECOND=4,MILLISECOND=111,ZONE_OFFSET=19800000,DST_OFFSET=0]


 Approach 2: IllegalArgumentException 

Java

import java.util.GregorianCalendar;

public class GregorianCalendarroll2 {
    public static void main(String[] args) {

        GregorianCalendar cal = new GregorianCalendar();

        int field = GregorianCalendar.DST_OFFSET, amount = 10;
        cal.roll(field, amount);
        System.out.println(cal);
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException at java.base/java.util.GregorianCalendar.roll(GregorianCalendar.java:1168)


No comments:

Post a Comment