AJM AJM - 11 months ago 59
Java Question

java.util.Date - Deleting three months from a date?

I have a date of type


I want to subtract three months from it.

Not finding a lot of joy in the API.

Answer Source

Here's the plain JDK version, it needs the Calendar class as a helper:

Date referenceDate = new Date();
Calendar c = Calendar.getInstance(); 
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:

new DateTime().minusMonths(3).toDate();

Or if you want to subtract from a given date instead of the current:

new DateTime(referenceDate).minusMonths(3).toDate();

Update for Java 8: With Java 8 you can also use the new JSR 310 API (which is inspired by Joda):