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

Date dt = new Date();

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


当前回答

在非常特殊的情况下,如果你要求做自己的约会课,可能是你的计算机编程教授;这个方法会做得很好。

public void addOneDay(){
    int [] months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    day++;
    if (day> months[month-1]){
        month++;
        day = 1;
        if (month > 12){
            year++;
            month = 1;
        }
    }
}

其他回答

Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));

Date有一个构造函数,使用自UNIX-epoch以来的毫秒数。getTime()-方法提供该值。所以把每一天的毫秒数加起来就可以了。如果你想定期做这样的操作,我建议为值定义常量。

重要提示:并非在所有情况下都是正确的。阅读下面的警告注释。

最佳用法:

      long currenTime = System.currentTimeMillis();
      long oneHourLater = currentTime + TimeUnit.HOURS.toMillis(1l);

类似地,你可以添加月、日、分钟等

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

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

Or

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

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

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

java8时间API:

Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);