How to subtract X days from a date using Java calendar? How to subtract X days from a date using Java calendar? java java

How to subtract X days from a date using Java calendar?


Taken from the docs here:

Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:

Calendar calendar = Calendar.getInstance(); // this would default to nowcalendar.add(Calendar.DAY_OF_MONTH, -5).


You could use the add method and pass it a negative number. However, you could also write a simpler method that doesn't use the Calendar class such as the following

public static void addDays(Date d, int days){    d.setTime( d.getTime() + (long)days*1000*60*60*24 );}

This gets the timestamp value of the date (milliseconds since the epoch) and adds the proper number of milliseconds. You could pass a negative integer for the days parameter to do subtraction. This would be simpler than the "proper" calendar solution:

public static void addDays(Date d, int days){    Calendar c = Calendar.getInstance();    c.setTime(d);    c.add(Calendar.DATE, days);    d.setTime( c.getTime().getTime() );}

Note that both of these solutions change the Date object passed as a parameter rather than returning a completely new Date. Either function could be easily changed to do it the other way if desired.


Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.

FYI in Joda Time you could do

DateTime dt = new DateTime();DateTime fiveDaysEarlier = dt.minusDays(5);