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

Date dt = new Date();

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


当前回答

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

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

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

其他回答

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

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;
        }
    }
}

这将使任何日期加1

String untildate="2011-10-08";//can take any date in current format    
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );   
Calendar cal = Calendar.getInstance();    
cal.setTime( dateFormat.parse(untildate));    
cal.add( Calendar.DATE, 1 );    
String convertedDate=dateFormat.format(cal.getTime());    
System.out.println("Date increase by one.."+convertedDate);

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

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

使用DateTime对象。加上任何你想要的时间等等。 希望这有用:)

正如在顶部的回答中提到的,自从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);