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

前端 未结 11 1588
北荒
北荒 2020-12-14 05:30

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.

11条回答
  •  情话喂你
    2020-12-14 06:20

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

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

    LocalDateTime.from(referenceDate.toInstant()).minusMonths(3);
    

提交回复
热议问题