Incrementing a java.util.Date by one day

Viewed 45932

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.

8 Answers
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 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

Related