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

如何将此日期增加一天?


当前回答

在java 8中,您可以使用java.time. localdate

LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1);   //Add one to the day field

您可以将其转换为java.util.Date对象,如下所示。

Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

您可以将LocalDate格式化为字符串,如下所示。

String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

其他回答

我更喜欢使用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对象,并没有对前一个对象本身进行更改。

如果您想添加一个时间单位,并且希望其他字段也增加,则可以安全地使用add方法。请看下面的例子:

SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.set(1970,Calendar.DECEMBER,31);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println(simpleDateFormat1.format(cal.getTime()));

将打印:

1970-12-31
1971-01-01
1970-12-31

看看Joda-Time (https://www.joda.org/joda-time/)。

DateTimeFormatter parser = ISODateTimeFormat.date();

DateTime date = parser.parseDateTime(dateString);

String nextDay = parser.print(date.plusDays(1));

只需在字符串中传递日期和接下来的天数

 private String getNextDate(String givenDate,int noOfDays) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        String nextDaysDate = null;
    try {
        cal.setTime(dateFormat.parse(givenDate));
        cal.add(Calendar.DATE, noOfDays);

       nextDaysDate = dateFormat.format(cal.getTime());

    } catch (ParseException ex) {
        Logger.getLogger(GR_TravelRepublic.class.getName()).log(Level.SEVERE, null, ex);
    }finally{
    dateFormat = null;
    cal = null;
    }

    return nextDaysDate;

}

对于Java SE 8或更高版本,您应该使用新的日期/时间API

 int days = 7;       
 LocalDate dateRedeemed = LocalDate.now();
 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");

 String newDate = dateRedeemed.plusDays(days).format(formatter);   
 System.out.println(newDate);

如果您需要从java.util.Date转换为java.time。LocalDate,您可以使用此方法。

  public LocalDate asLocalDate(Date date) {
      Instant instant = date.toInstant();
      ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
      return zdt.toLocalDate();
  }

对于Java SE 8之前的版本,您可以使用Joda-Time

Joda-Time提供了Java日期和时间的高质量替代品 类,是Java事实上的标准日期和时间库 在Java SE 8之前

   int days = 7;       
   DateTime dateRedeemed = DateTime.now();
   DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/uuuu");
        
   String newDate = dateRedeemed.plusDays(days).toString(formatter);   
   System.out.println(newDate);