Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment existing date by 1 day [duplicate]

Tags:

java

date

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

like image 346
Megatron Avatar asked Feb 26 '11 20:02

Megatron


3 Answers

Calendar c = Calendar.getInstance();
c.setTime(yourdate);
c.add(Calendar.DATE, 1);
Date newDate = c.getTime();
like image 152
MeBigFatGuy Avatar answered Oct 21 '22 11:10

MeBigFatGuy


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.

like image 37
Paŭlo Ebermann Avatar answered Oct 21 '22 10:10

Paŭlo Ebermann


org.apache.commons.lang.time.DateUtils.addDays(date, 1);
like image 44
Tomasz Nurkiewicz Avatar answered Oct 21 '22 09:10

Tomasz Nurkiewicz