我使用的日期格式为:yyyy-mm-dd。

如何将此日期增加一天?


当前回答

使用DateFormat API将字符串转换为日期对象,然后使用Calendar API添加一天。如果您需要特定的代码示例,请告诉我,我可以更新我的答案。

其他回答

Date today = new Date();               
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd");            
Calendar c = Calendar.getInstance();        
c.add(Calendar.DATE, 1);  // number of days to add      
String tomorrow = (String)(formattedDate.format(c.getTime()));
System.out.println("Tomorrows date is " + tomorrow);

这将给出明天的日期。C.add(…)参数可以从1更改为另一个数字,以获得适当的增量。

我更喜欢使用Apache的DateUtils。查看这个http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html。它很方便,特别是当你必须在你的项目中多个地方使用它,而不想为此编写你的一行方法时。

API说:

addDays(Date Date, int amount):在返回新对象的日期上添加天数。

注意,它返回一个新的Date对象,并没有对前一个对象本身进行更改。

java.time

在Java 8及以后的版本中,Java。时间包让这个过程变得很自动。(教程)

假设字符串输入和输出:

import java.time.LocalDate;

public class DateIncrementer {
  static public String addOneDay(String date) {
    return LocalDate.parse(date).plusDays(1).toString();
  }
}
Date newDate = new Date();
newDate.setDate(newDate.getDate()+1);
System.out.println(newDate);
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender