views:

6637

answers:

6

Anyone know a simple way using java calendar to subtract X days to a date?

Sry not being able to find any function which allows me to directly subtract X days to a date in java, if anyone could point me into the correct direction.

+8  A: 

Taken from the docs here: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html

Date Arithmetic function. Adds the specified (signed) amount of time to the given time 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:

add(Calendar.DATE, -5).

Anson Smith
Just be careful doing this since it doesn't always roll like you expect it to.
carson
sh*t i was looking for subtract when reading that and totaly forgot the existance of add, ty
fmsf
+1  A: 
int x = -1;
Calendar cal = ...;
cal.add(Calendar.DATE, x);

edit: the parser doesn't seem to like the link to the Javadoc, so here it is in plaintext:

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html#add(int, int)

matt b
+1  A: 

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() + 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();
    Calendar.setTime(d);
    Calendar.add(Calendar.DATE, days);
    d.setTime( Calendar.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.

Eli Courtwright
+9  A: 

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);
Mike Deck
A: 

thanks all, and you can give me down votes for being an idiot that couldn't read :S

still thanks the same :)

fmsf
A: 

Eli Courtwright second solution is wrong, it should be:

Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -days);
date.setTime(c.getTime().getTime());
The name of the function in Eli's solution is `addDays`; his solution is correct. If you want to subtract days from the date, you pass in a negative value for `days`.
Thomas Upton
Well, that is something that the programmer has to specify when creating the function, no? :P