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 isCalendar.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 isCalendar.DATE
. - We can get the time that this calendar object represents every time that it is changed , using
get(int field)
API method, withCalendar.MONTH
,Calendar.DATE
andCalendar.YEAR
as fields. Every time after the calendar is changed, the value for theDATE
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.