Java Date Time - Java Calendar.add(int field, int amount)








Syntax

Calendar.add(int field, int amount) has the following syntax.

public abstract void add(int field, int amount)

Example

In the following code shows how to use Calendar.add(int field, int amount) method.

/*from  ww w. ja  va  2  s . c o m*/
import java.util.Calendar;

public class Main {

   public static void main(String[] args) {
   
      Calendar cal = Calendar.getInstance();
    
      System.out.println("The current date is : " + cal.getTime());

      // add 20 days to the calendar
      cal.add(Calendar.DATE, 20);
      System.out.println("20 days later: " + cal.getTime());

      // subtract 2 months from the calendar
      cal.add(Calendar.MONTH, -2);
      System.out.println("2 months ago: " + cal.getTime());

      // subtract 5 year from the calendar
      cal.add(Calendar.YEAR, -5);
      System.out.println("5 years ago: " + cal.getTime());
   }
}

The code above generates the following result.