我想在一个特定的日期上加上一天。我该怎么做呢?
Date dt = new Date();
现在我想在这个日期上加一天。
我想在一个特定的日期上加上一天。我该怎么做呢?
Date dt = new Date();
现在我想在这个日期上加一天。
当前回答
java8时间API:
Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);
其他回答
为了使它与java无关,基本原则是转换为某种线性日期格式,儒略日、修改的儒略日、从某个纪元开始的秒等,添加您的日期,然后转换回来。
这样做的原因是,您可以将“正确处理闰日、闰秒等”的问题外包给那些运气好的人,他们没有把这个问题搞砸。
我要提醒您,正确使用这些转换例程可能很困难。人们搞砸时间的方式多得惊人,最近一个高调的例子是微软的Zune。不要取笑MS,因为它很容易搞砸。即使有多种不同的时间格式,比如TAI和TT,也无济于事。
你可以像这样尝试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 Date getToDateAfterDays(Integer day) {
Date nowdate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(nowdate);
cal.add(Calendar.DATE, day);
return cal.getTime();
}
正如在顶部的回答中提到的,自从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);
java8时间API:
Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);