我想在一个特定的日期上加上一天。我该怎么做呢?

Date dt = new Date();

现在我想在这个日期上加一天。


当前回答

我更喜欢用joda来计算日期和时间,因为它可读性更好:

Date tomorrow = now().plusDays(1).toDate();

Or

endOfDay(now().plus(days(1))).toDate()
startOfDay(now().plus(days(1))).toDate()

其他回答

正如在顶部的回答中提到的,自从java 8以来,它可以做到:

Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);

但这有时会导致像这样的DateTimeException:

java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2014-11-29T03:20:10.800Z of type java.time.Instant

可以通过简单地传递时区来避免此异常:

LocalDateTime.from(dt.toInstant().atZone(ZoneId.of("UTC"))).plusDays(1);

您可以在导入org.apache.commons.lang.time.DateUtils后使用此方法:

DateUtils.addDays(new Date(), 1);

Java 8 LocalDate API

LocalDate.now().plusDays(1L);

你想在几天后找到日期这个代码尝试..

public Date getToDateAfterDays(Integer day) {
        Date nowdate = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(nowdate);
        cal.add(Calendar.DATE, day);
        return cal.getTime();
    }

我将向您展示如何在Java 8中做到这一点。给你:

public class DemoDate {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Current date: " + today);

        //add 1 day to the current date
        LocalDate date1Day = today.plus(1, ChronoUnit.DAYS);
        System.out.println("Date After 1 day : " + date1Day);
    }
}

输出:

Current date: 2016-08-15
Date After 1 day : 2016-08-16