我想在一个特定的日期上加上一天。我该怎么做呢?
Date dt = new Date();
现在我想在这个日期上加一天。
我想在一个特定的日期上加上一天。我该怎么做呢?
Date dt = new Date();
现在我想在这个日期上加一天。
当前回答
我将向您展示如何在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
其他回答
在非常特殊的情况下,如果你要求做自己的约会课,可能是你的计算机编程教授;这个方法会做得很好。
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;
}
}
}
使用DateTime对象。加上任何你想要的时间等等。 希望这有用:)
你可以像这样尝试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,因为你只想添加一天。
更多信息可以在本文档中找到。
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无关,基本原则是转换为某种线性日期格式,儒略日、修改的儒略日、从某个纪元开始的秒等,添加您的日期,然后转换回来。
这样做的原因是,您可以将“正确处理闰日、闰秒等”的问题外包给那些运气好的人,他们没有把这个问题搞砸。
我要提醒您,正确使用这些转换例程可能很困难。人们搞砸时间的方式多得惊人,最近一个高调的例子是微软的Zune。不要取笑MS,因为它很容易搞砸。即使有多种不同的时间格式,比如TAI和TT,也无济于事。