我想在一个特定的日期上加上一天。我该怎么做呢?
Date dt = new Date();
现在我想在这个日期上加一天。
我想在一个特定的日期上加上一天。我该怎么做呢?
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;
}
}
}
其他回答
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以来,它可以做到:
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);
我发现了一个简单的方法,可以向Date对象添加任意时间
Date d = new Date(new Date().getTime() + 86400000)
地点:
86 400 000 ms = 1 Day : 24*60*60*1000
3 600 000 ms = 1 Hour : 60*60*1000
最佳用法:
long currenTime = System.currentTimeMillis();
long oneHourLater = currentTime + TimeUnit.HOURS.toMillis(1l);
类似地,你可以添加月、日、分钟等
您可以在导入org.apache.commons.lang.time.DateUtils后使用此方法:
DateUtils.addDays(new Date(), 1);