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.
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.
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).
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)
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.
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);
thanks all, and you can give me down votes for being an idiot that couldn't read :S
still thanks the same :)
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());