Incrementing a java.util.Date by one day

前端 未结 8 1044

What is the correct way to increment a java.util.Date by one day.

I\'m thinking something like

        Calendar cal = Calendar.getInstance();
        ca         


        
8条回答
  •  不思量自难忘°
    2021-02-07 01:59

    If you do not like the math in the solution from Tony Ennis

    Date someDate = new Date(); // Or whatever
    Date dayAfter = new Date(someDate.getTime() + TimeUnit.DAYS.toMillis( 1 ));
    

    But more or less since finding this Q/A, I have been using JodaTime, instead, and have recently switched to the new DateTime in Java 8 (which inspired by but not copied from Joda - thanks @BasilBourqueless for pointing this out).

    Java 8

    In Java 8, almost all time-based classes have a .plusDays() method making this task trivial:

    LocalDateTime.now()  .plusDays(1);
    LocalDate.now()      .plusDays(1);
    ZonedDateTime.now()  .plusDays(1);
    Duration.ofDays(1)   .plusDays(1);
    Period.ofYears(1)    .plusDays(1);
    OffsetTime.now()     .plus(1, ChronoUnit.DAYS);
    OffsetDateTime.now() .plus(1, ChronoUnit.DAYS);
    Instant.now()        .plus(1, ChronoUnit.DAYS);
    

    Java 8 also added classes and methods to interoperate between the (now) legacy Date and Calendar etc. and the new DateTime classes, which are most certainly the better choice for all new development.

提交回复
热议问题