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

Date dt = new Date();

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


当前回答

Java 1.8版本对数据时间API进行了很好的更新。

下面是一段代码:

    LocalDate lastAprilDay = LocalDate.of(2014, Month.APRIL, 30);
    System.out.println("last april day: " + lastAprilDay);
    LocalDate firstMay = lastAprilDay.plusDays(1);
    System.out.println("should be first may day: " + firstMay);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
    String formatDate = formatter.format(firstMay);
    System.out.println("formatted date: " + formatDate);

输出:

last april day: 2014-04-30
should be first may day: 2014-05-01
formatted date: 01

要了解更多信息,请参阅此类的Java文档:

LocalDate DateTimeFormatter

其他回答

Java 8 LocalDate API

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

这将使任何日期加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);

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

我将向您展示如何在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
Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));

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

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