Java How To Add Substract Date Day Month Or Year

Have a doubt on how to add or substract dates in Java? Use the Calendar class.

The methods add() and roll() are used to add or substract values to a Calendar object.

You have to specify which Calendar field is to be affected by the operation (Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

add() adds or substracts values to the specified Calendar field, the next larger field is modified when the result makes the Calendar "rolls over".

String DATE_FORMAT = "dd/MM/yyyy";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance(); 
 
//Calendar has default current time and date
// To set another date user c1.set(2000, 0, 21);  // Remember month is from 0 to 11, i.e 0 - Jan, 11-Dec
 
c1.add(Calendar.DATE,20); // Add the date by 20 days
System.out.println("Date 20 days from now is "+sdf.format(c1.getTime()));

roll() does the same thing except you specify if you want to roll up (add 1) or roll down (substract 1) to the specified Calendar field. The operation only affects the specified field while add() adjusts other Calendar fields. See the following example, roll() makes january rolls to december in the same year while add() substract the YEAR field for the correct result.

Calendar c1 = Calendar.getInstance(); 
// roll down the month
c1.set(1999, 0 , 20); // 1999 jan 20
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.roll(Calendar.MONTH, false); // roll down, substract 1 month
System.out.println("Date roll down 1 month : " + sdf.format(c1.getTime())); // 1999 jan 20
 
c1.set(1999, 0 , 20); // 1999 jan 20 
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -1); // substract 1 month
System.out.println("Date minus 1 month : " + sdf.format(c1.getTime())); // 1998 dec 20
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License