Java Utility Library

Java Calendar - add() Method



The java.util.Calendar.add() method is used to add or subtract the specified amount of time to the given calendar field, based on the calendar's rules.

Syntax

public abstract void add(int field,
                         int amount)

Parameters

field Specify the calendar field.
amount Specify the amount of date or time to be added to the field.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.Calendar.add() method is used to add or subtract the specified amount of time to the given field.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a Calendar with specified date
    Calendar Cal = new GregorianCalendar(2018, 10, 25);

    //printing the calendar
    System.out.println("The Calendar is: " + Cal.getTime());

    //add 5 days from the calendar object
    Cal.add(Calendar.DAY_OF_MONTH, 5);

    //printing the calendar
    System.out.println("New Calendar is: " + Cal.getTime());

    //subtract 5 years from the calendar object
    Cal.add(Calendar.YEAR, -5);

    //printing the calendar
    System.out.println("New Calendar is: " + Cal.getTime()); 
  }
}

The output of the above code will be:

The Calendar is: Sun Nov 25 00:00:00 UTC 2018
New Calendar is: Fri Nov 30 00:00:00 UTC 2018
New Calendar is: Sat Nov 30 00:00:00 UTC 2013

❮ Java.util - Calendar