add(int, int): This method is available in java.util.GregorianCalendar class of Java.
Syntax:
void java.util.GregorianCalendar.add(int field, int amount)
This method takes two arguments of type int as its parameters. This method adds the specified amount of time to the given calendar field, based on the calendar's rules.
Parameters: Two parameters are required for this method.
field: the calendar field.
amount: the amount of date or time to be added 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 GregorianCalendaradd {public static void main(String[] args) {GregorianCalendar cal = (GregorianCalendar)GregorianCalendar.getInstance();cal.add(GregorianCalendar.MONTH, 2);System.out.println(cal.getTime());}}
Output:
Tue Apr 05 12:00:45 IST 2022
Approach 2: IllegalArgumentException
Java
import java.util.GregorianCalendar;public class GregorianCalendaradd {public static void main(String[] args) {GregorianCalendar cal = (GregorianCalendar)GregorianCalendar.getInstance();cal.add(GregorianCalendar.ZONE_OFFSET, 2);System.out.println(cal.getTime());}}
Output:
Exception in thread "main" java.lang.IllegalArgumentException at java.base/java.util.GregorianCalendar.add(GregorianCalendar.java:920)
No comments:
Post a Comment