How to add or subtract datetime in java with examples

Here we will learn how to add or subtract date time from given date.

Here we will use Calendar class from java.util package. It is an abstract class which provided method for manipulating the calendar field. We will use add(int field, int amount) method from this class. Which can be used to adds or subtracts the specified amount of time to the given calendar field, based on the calendar’s rules.

field is the calendar field.

amount is  the amount of date or time to be added/subtract to the field.

 

import java.util.Calendar;

public class AddOrSubtractDate {

	public static void main(String args[]) {

		Calendar calendar = Calendar.getInstance();

		System.out.println("Today : " + calendar.getTime());

		/*
		 * Subtracting 10 days from the calendar Now Calendar field would be
		 * Calendar.DATE
		 */
		calendar.add(Calendar.DATE, -10);
		System.out.println("10 days back: " + calendar.getTime());

		/*
		 * Adding 10 days. Now date will be todays date
		 */
		calendar.add(Calendar.DATE, 10);
		System.out.println("10 days later: " + calendar.getTime());

		/*
		 * Add 1 months to the calendar
		 */
		calendar.add(Calendar.MONTH, 1);
		System.out.println("1 month later: " + calendar.getTime());

		// Subtract 1 year from the calendar
		calendar.add(Calendar.YEAR, -1);
		System.out.println("1 year ago: " + calendar.getTime());
	}
}

Output would be

 

Today : Sat Jul 21 19:24:04 IST 2012
10 days back: Wed Jul 11 19:24:04 IST 2012
10 days later: Sat Jul 21 19:24:04 IST 2012
1 month later: Tue Aug 21 19:24:04 IST 2012
1 year ago: Sun Aug 21 19:24:04 IST 2011

 

4 Comments

    • Hi Vishal,

      I have checked, it is visible. Except comment every part of the code is visible which is accepted.
      Meanwhile you can find the attached code in Mail.

      Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

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