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

 

By | 2012-07-21T13:55:09+00:00 July 21st, 2012|Code Base|3 Comments

About the Author:

3 Comments

  1. vishal April 2, 2013 at 2:01 pm - Reply

    change color of your text its not visible

    • admin April 2, 2013 at 3:05 pm - Reply

      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

  2. Anil Nivargi September 3, 2014 at 5:20 pm - Reply

    Thanks nice code…For more Java Date and Calendar examples please go through this blog http://adnjavainterview.blogspot.in/2014/08/java-date-and-calendar-examples.html

Leave A Comment