Calendar

Add/Subtract Months from Date with Calendar

With this example we are going to demonstrate how to add and subtract Months from a Date using the Calendar class, that allows us to convert between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR. In short, to add and subtract Months from a Date using the Calendar class you should:

  • Create a new Calendar object, using getInstance() API method of Calendar, that gets a calendar using the default time zone and locale.
  • Use add(int field, int amount) API method of Calendar to add an int amount of time to the given calendar field, that is Calendar.MONTH.
  • Use add(int field, int amount) API method of Calendar again, this time to subtract an int amount of time to the given calendar field, that is Calendar.MONTH.
  • We can get the time that this calendar object represents every time that it is changed , using get(int field) API method, with Calendar.MONTH, Calendar.DATE and Calendar.YEAR as fields. Every time after the calendar is changed, the values for the MONTH and YEAR fields will be different.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.Calendar;

public class AddSubtractDateMonths {

	public static void main(String[] args) {

		int monthsToAdd = 4;
		int monthsToSubtract = 10;

		Calendar c = Calendar.getInstance();

		System.out.println("Current date : " + (c.get(Calendar.MONTH) + 1) +
				"-" + c.get(Calendar.DATE) + "-" + c.get(Calendar.YEAR));

		// add months to current date
		c.add(Calendar.MONTH, monthsToAdd);

		System.out.println("Date (after): " + (c.get(Calendar.MONTH) + 1) +
				"-" + c.get(Calendar.DATE) + "-" + c.get(Calendar.YEAR));

		c = Calendar.getInstance();

		c.add(Calendar.MONTH, -monthsToSubtract);

		System.out.println("Date (before): " + (c.get(Calendar.MONTH) + 1) +
				"-" + c.get(Calendar.DATE) + "-" + c.get(Calendar.YEAR));

	}

}

Output:

Current date : 10-19-2011 Date (after): 2-19-2012 Date (before): 12-19-2010

 
This was an example of how to add and subtract Months from a Date using the Calendar class in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button