JAVA – How to Add or Subtract Date

 

In calendar, date can add and subtract with add method of Calendar in java. Java.util.Calendar class has a method to set date in object and after that we can add or subtract date according to requirement. We can add or subtract month, year and date with date option.

To subtract date, value should be passed with negative (-). This will reduce date from date.
To add date, value should be passed in positive. This will increase date from date.

In java program, we are adding 23 days in date. Month and Year is kept commented, will show that how to use add month and add year in date. To use this just do comment year and month.

First we are setting date in Calendar.

ca1.set(Year,Month,Date)

Adding & Subtracting Date

ca1.add(field, Value)

field = Calendar.DATE
field = Calendar.MONTH
field = Calendar.YEAR
value = any numeric value

 

import java.util.Calendar;

public class AddDate {

    public static void main(String[] args) {

    Calendar ca1 = Calendar.getInstance();
    ca1.set(2009,05,25);

    // Addition of date in java        
    ca1.add(Calendar.DATE, 23); // Add 23 days in Dates in Calendar
    //ca1.add(Calendar.MONTH, 2); // Add 2 Month in Date in Calendar
    //ca1.add(Calendar.YEAR, 4); // Add 4 Year in Date in Calendar

    /*
     *  Subtracting Date in Calendar
     *  
     *  ca1.add(Calendar.DATE, -23); // Subtracting 23 days from date
     *  //ca1.add(Calendar.MONTH, -2); // Subtracting 2 Month in Date in Calendar
     *  //ca1.add(Calendar.YEAR, -4); // Subtracting 4 Year in Date in Calendar
     */

    System.out.println("Date :"+ca1.get(Calendar.DATE));
    System.out.println("Month :"+ca1.get(Calendar.MONTH));
    System.out.println("Year :"+ca1.get(Calendar.YEAR));
    }
}

Output

Date :18

Month :6

Year :2009

Tags:

 

4 Responses to “JAVA – How to Add or Subtract Date”

  1. mostafa says:

    thanks or help
    but r u try subtract

    ca1.set(2011,12,1);
    ca1.add(Calendar.DATE, 1);

    and

    ca1.set(2011,12,2);
    ca1.add(Calendar.DATE, 1);

  2. Chakri says:

    Thanks for the date fn

    Thanks a lot

    very simple code

  3. Jeeva says:

    Thanks a lot

  4. Nakul says:

    Its not working.
    Calendar ca1 = Calendar.getInstance();
    ca1.set(2013,12,27);

    System.out.println(“Month :”+ca1.get(Calendar.MONTH));
    System.out.println(“Year :”+ca1.get(Calendar.YEAR));
    This code should produce following output :
    Month : 12
    Year : 2013

    but i am getting :
    Month : 0
    Year : 2014

Leave a Reply