.add()
Published Sep 18, 2023
Contribute to Docs
The .add()
method of the Calendar
class is used to manipulate and modify a Calendar
instance by adding or subtracting a specified amount of time to/from a specific calendar field.
Syntax
myCalendar.add(field, amount)
field
: An integer constant representing the field to which the amount of time should be added or subtracted (e.g.,Calendar.YEAR
,Calendar.MONTH
,Calendar.DAY_OF_MONTH
).amount
: An integer value representing the amount of time to add or subtract from the specified field. A positive value adds time, and a negative value subtracts time.
Example
The example below demonstrates how to use the .add()
method to manipulate a Calendar
instance:
import java.util.Calendar;public class Main {public static void main(String[] args) {// Create a Calendar instance representing the current date and timeCalendar myCalendar = Calendar.getInstance();// Add 2 years to the current datemyCalendar.add(Calendar.YEAR, 2);System.out.println("Modified Date after adding 2 years: " + myCalendar.getTime());// Add 3 months to the current datemyCalendar.add(Calendar.MONTH, 3);System.out.println("Modified Date after adding 3 months: " + myCalendar.getTime());// Subtract 10 days from the current datemyCalendar.add(Calendar.DAY_OF_MONTH, -10);System.out.println("Modified Date after subtracting 10 days: " + myCalendar.getTime());}}
Output for the above code will vary depending on the current date but will look similar to:
Modified Date after adding 2 years: Tue Sep 16 11:07:52 CEST 2025Modified Date after adding 3 months: Tue Dec 16 11:07:52 CET 2025Modified Date after subtracting 10 days: Sat Dec 06 11:07:52 CET 2025
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours