Java.util.Calendar.add() Method


Description

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

Declaration

Following is the declaration for java.util.Calendar.add() method

public abstract void add(int field,int amount)

Parameters

  • field − the calendar field.

  • amount −the amount of date or time to be added to the field.

Return Value

This method does not return any value.

Exception

NA

Example

The following example shows the usage of java.util.Calendar.Add() method.

package com.tutorialspoint;
import java.util.Calendar;

public class CalendarDemo {
   public static void main(String[] args) {
   
      // create a calendar
      Calendar cal = Calendar.getInstance();

      // print current date
      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());
   }
}

Let us compile and run the above program, this will produce the following result −

The current date is : Thu Apr 26 02:13:28 EEST 2012
20 days later: Wed May 16 02:13:28 EEST 2012
2 months ago: Fri Mar 16 02:13:28 EET 2012
5 years ago: Fri Mar 16 02:13:28 EET 2007
java_util_calendar.htm
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements