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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With