How to subtract X days from a date using Java calendar?

后端 未结 10 1261
無奈伤痛
無奈伤痛 2020-11-22 15:40

Anyone know a simple way using Java calendar to subtract X days from a date?

I have not been able to find any function which allows me to directly subtract X days fr

10条回答
  •  感动是毒
    2020-11-22 15:44

    I believe a clean and nice way to perform subtraction or addition of any time unit (months, days, hours, minutes, seconds, ...) can be achieved using the java.time.Instant class.

    Example for subtracting 5 days from the current time and getting the result as Date:

    new Date(Instant.now().minus(5, ChronoUnit.DAYS).toEpochMilli());
    

    Another example for subtracting 1 hour and adding 15 minutes:

    Date.from(Instant.now().minus(Duration.ofHours(1)).plus(Duration.ofMinutes(15)));
    

    If you need more accuracy, Instance measures up to nanoseconds. Methods manipulating nanosecond part:

    minusNano()
    plusNano()
    getNano()
    

    Also, keep in mind, that Date is not as accurate as Instant.

提交回复
热议问题