tags:

views:

233

answers:

4

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.

+8  A: 
    Calendar cal = Calendar.getInstance();
 cal.setTime(new Date());
 cal.add(Calendar.MONTH, -3);

set your date using setTime method.

Firstthumb
"set your date using setTime method" - and in that simple sentence is the summation of all that is wrong with java.util.Date :-)
Brian Agnew
What is wrong with java.util.Date
Firstthumb
I just give quick answer and post a sample code. I think It is helpful for question.
Firstthumb
@Firstthumb: The most important problems is that Date is not immutable. The setter shows that problem. But contrary to Brian's comment there are other problems. See the Joda site for some explanations on why they created the Joda library.
DR
java.util.Date is standard for java. You are right. Its performance is not good. But I insist on that my answer is one of the solutions to AJM's question
Firstthumb
A: 

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.

Everyone
Is there a reason why you do GregorianCalendar lCalendar = new GregorianCalendar(); instead of Calendar lCalendar = Calendar.getInstance()?
Jesper
+7  A: 

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();
DR
+2  A: 

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);
Brian Agnew