I have a date of type java.util.Date
I want to subtract three months from it.
Not finding a lot of joy in the API.
I have a date of type java.util.Date
I want to subtract three months from it.
Not finding a lot of joy in the API.
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.MONTH, -3);
set your date using setTime method.
The Date class itself isn't enough (+: You've got to use the Calendar class here
Something along these lines
GregorianCalendar lCalendar = new GregorianCalendar();
lCalendar.setTime( aDate );
lCalendar.add(Calendar.MONTH, -3);
p.s. the snippet above is not tested to be compilable.
Here's the plain JDK version, it needs the Calendar class as a helper:
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH, -3);
return c.getTime();
But you should seriously consider using the Joda library, because of various shortcomings of the Date and Calendar classes. With Joda you can do the following:
return new DateTime().minusMonths(3).toDate();
Or if you want to subtract from a given date instead of the current:
return new DateTime(referenceDate).minusMonths(3).toDate();
I always recommend Joda for this sort of stuff. It has a much nicer API, and doesn't suffer from threading issues that the standard Java date/time has (e.g. issues with SimpleDateFormat, or general mutability).
e.g.
DateTime result = dt.minusMonths(3);