What is the correct way to increment a java.util.Date by one day.
I\'m thinking something like
Calendar cal = Calendar.getInstance();
ca
I am contributing the modern answer.
It doesn't 'feel' right.
My suggestion is that why it doesn’t feel right is because it’s so verbose. Adding one day to a date is conceptually a simple thing to do and ought to have a simple representation in your program. The problem here is the poor design of the Calendar
class: when you use it, your code needs to be this verbose. And you are correct: you should not use the poorly designed Calendar
class. It’s long outdated. Using java.time, the modern Java date and time API, adding one day is simple, also in code:
LocalDate toDate = LocalDate.of(2020, Month.FEBRUARY, 28);
LocalDate nextDate = toDate.plusDays(1);
System.out.println("Incremented date is " + nextDate);
Output is:
Incremented date is 2020-02-29
In case your need is for a different type than LocalDate
, other java.time classes also have a plusDays
method that you can use in the same way, as already shown in the answer by Ivin.
Links
That would work.
It doesn't 'feel' right.
If it is the verbosity that bothers you, welcome to the Java date-time API :-)
Here's how I do it:
Date someDate = new Date(); // Or whatever
Date dayAfter = new Date(someDate.getTime()+(24*60*60*1000));
Where the math at the end converts a day's worth of seconds to milliseconds.
Date thisDate = new Date(System.currentTimeMillis());
Date dayAfter = new Date(thisDate.getTime() + TimeUnit.DAYS.toMillis( 1 ));
Date dayBefore = new Date(thisDate.getTime() + TimeUnit.DAYS.toMillis( -1 ));
I believe joda time library makes it much more clean to work with dates.
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).
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.