Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing a java.util.Date by one day

Tags:

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.

like image 559
Anthony Avatar asked Sep 28 '10 01:09

Anthony


People also ask

How can I increase my one day date?

Date today = new Date(); Date tomorrow = new Date(today. getTime() + (1000 * 60 * 60 * 24));

How do I add 7 days to Java Util date?

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.

How can I decrement a date by one day in Java?

DateTime yesterday = new DateTime(). minusDays(1);


2 Answers

That would work.

It doesn't 'feel' right.

If it is the verbosity that bothers you, welcome to the Java date-time API :-)

like image 145
Thilo Avatar answered Sep 26 '22 19:09

Thilo


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.

like image 36
Ivin Avatar answered Sep 26 '22 19:09

Ivin