10

Possible Duplicate:
How can I increment a date by one day in Java?

I have an existing date object that I'd like to increment by one day while keeping every other field the same. Every example I've come across sheds hours/minutes/seconds or you have to create a new date object and transfers the fields over. Is there a way you can just advance the day field by 1?

Thanks

EDIT: Sorry i didn't mean increment the value of the day by one, i meant advance the day forward by 1

Community
  • 1
  • 1
Megatron
  • 2,871
  • 4
  • 40
  • 58
  • 1
    No. The only way is to add 1 day to the date. The reason: suppose you increment the date field of May 31 by 1. Would that make it May 32? Whereas if you add 1 day, Java takes care of that. – Soumya Feb 26 '11 at 20:57
  • 2
    Something like `date.setTime(date.getTime() + 24*60*60*1000)` is a simple dirty solution. – maaartinus Feb 26 '11 at 22:32
  • 1
    w/o a timezone specified there is no current date. – bestsss Feb 26 '11 at 23:19

3 Answers3

28
Calendar c = Calendar.getInstance();
c.setTime(yourdate);
c.add(Calendar.DATE, 1);
Date newDate = c.getTime();
MeBigFatGuy
  • 28,272
  • 7
  • 61
  • 66
6

The Date object itself (assuming you mean java.util.Date) has no Day field, only a "milliseconds since Unix Epoch" value. (The toString() method prints this depending on the current locale.)

Depending of what you want to do, there are in principle two ways:

  • If you want simply "precisely 24 hours after the given date", you could simply add 1000 * 60 * 60 * 24 milliseconds to the time value, and then set this. If there is a daylight saving time shift between, it could then be that your old date was on 11:07 and the new is on 10:07 or 12:07 (depending of the direction of shift), but it still is exactly 24 hours difference.

    private final static long MILLISECONDS_PER_DAY = 1000L * 60 * 60 * 24;
    
    /**
     * shift the given Date by exactly 24 hours.
     */
    public static void shiftDate(Date d) {
        long time = d.getTime();
        time += MILLISECONDS_PER_DAY;
        d.setTime(time);
    }
    
  • If you want to have "the same time on the next calendar day", you better use a Calendar, like MeBigFatGuy showed. (Maybe you want to give this getInstance() method the TimeZone, too, if you don't want your local time zone to be used.)

    /**
     * Shifts the given Date to the same time at the next day.
     * This uses the current time zone.
     */
    public static void shiftDate(Date d) {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.add(Calendar.DATE, 1);
        d.setTime(c.getTimeInMillis());
    }
    

    If you are doing multiple such date manipulations, better use directly a Calendar object instead of converting from and to Date again and again.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
5
org.apache.commons.lang.time.DateUtils.addDays(date, 1);
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674