我想在一个特定的日期上加上一天。我该怎么做呢?
Date dt = new Date();
现在我想在这个日期上加一天。
我想在一个特定的日期上加上一天。我该怎么做呢?
Date dt = new Date();
现在我想在这个日期上加一天。
当前回答
Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));
Date有一个构造函数,使用自UNIX-epoch以来的毫秒数。getTime()-方法提供该值。所以把每一天的毫秒数加起来就可以了。如果你想定期做这样的操作,我建议为值定义常量。
重要提示:并非在所有情况下都是正确的。阅读下面的警告注释。
其他回答
使用DateTime对象。加上任何你想要的时间等等。 希望这有用:)
给定一个Date dt,你有几种可能性:
解决方案1:你可以使用Calendar类:
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
解决方案2:您应该认真考虑使用Joda-Time库,因为Date类存在各种缺点。使用Joda-Time你可以做以下事情:
Date dt = new Date();
DateTime dtOrg = new DateTime(dt);
DateTime dtPlusOne = dtOrg.plusDays(1);
解决方案3:在Java 8中,你还可以使用新的JSR 310 API(它的灵感来自Joda-Time):
Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);
最佳用法:
long currenTime = System.currentTimeMillis();
long oneHourLater = currentTime + TimeUnit.HOURS.toMillis(1l);
类似地,你可以添加月、日、分钟等
你可以像这样尝试java.util.Date库-
int no_of_day_to_add = 1;
Date today = new Date();
Date tomorrow = new Date( today.getYear(), today.getMonth(), today.getDate() + no_of_day_to_add );
根据需要更改no_of_day_to_add的值。
我设置了no_of_day_to_add的值为1,因为你只想添加一天。
更多信息可以在本文档中找到。
在非常特殊的情况下,如果你要求做自己的约会课,可能是你的计算机编程教授;这个方法会做得很好。
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;
}
}
}