What is the correct way to increment a java.util.Date by one day.
I'm thinking something like
Calendar cal = Calendar.getInstance(); cal.setTime(toDate); cal.add(Calendar.DATE, 1); toDate = cal.getTime();
It doesn't 'feel' right.
Date today = new Date(); Date tomorrow = new Date(today. getTime() + (1000 * 60 * 60 * 24));
add functions move the date forward (or back, if you give a negative number) from the current value of the date. So add(Calendar. DATE, 7) adds 7 days to the current value.
DateTime yesterday = new DateTime(). minusDays(1);
That would work.
It doesn't 'feel' right.
If it is the verbosity that bothers you, welcome to the Java date-time API :-)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With