Calendar

Add/Subtract Days from Date with Calendar

This is an example of how to add and subtract Days from a Date using the Calendar, that provides methods to convert between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR. Adding and subtracting Days from a Date using the Calendar implies that 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.DATE.
  • 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.DATE.
  • 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 value for the DATE field 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 AddSubtractDateDays {

	public static void main(String[] args) {

		int daysToAdd = 4;
		int daysToSubtract = 10;

		Calendar c = Calendar.getInstance();

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

		// add days to current date
		c.add(Calendar.DATE, daysToAdd);

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

		c = Calendar.getInstance();

		c.add(Calendar.DATE, -daysToSubtract);

		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): 10-23-2011 Date (before): 10-9-2011

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

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron 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