开发者

Increment existing date by 1 day [duplicate]

开发者 https://www.devze.com 2023-02-13 10:45 出处:网络
This question already has answers here: Closed 11 years 开发者_如何学运维ago. Possible Duplicate:
This question already has answers here: Closed 11 years 开发者_如何学运维ago.

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


Calendar c = Calendar.getInstance();
c.setTime(yourdate);
c.add(Calendar.DATE, 1);
Date newDate = c.getTime();


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.


org.apache.commons.lang.time.DateUtils.addDays(date, 1);
0

精彩评论

暂无评论...
验证码 换一张
取 消