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

如何将此日期增加一天?


当前回答

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

 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;

}

其他回答

请注意这一行增加了24小时:

d1.getTime() + 1 * 24 * 60 * 60 * 1000

但是这条线增加了一天

cal.add( Calendar.DATE, 1 );

在夏令时改变的日子里(25或23小时),你会得到不同的结果!

如果你使用的是Java 8, Java .time. localdate和Java .time.format. datetimeformatter可以让这个工作变得非常简单。

public String nextDate(String date){
      LocalDate parsedDate = LocalDate.parse(date);
      LocalDate addedDate = parsedDate.plusDays(1);
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
      return addedDate.format(formatter); 
}

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

你可以使用"org.apache.commons.lang3.time"中的这个包:

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 Date myNewDate = DateUtils.addDays(myDate, 4);
 Date yesterday = DateUtils.addDays(myDate, -1);
 String formatedDate = sdf.format(myNewDate);  

自Java 1.5以来,TimeUnit.DAYS.toMillis(1)对我来说看起来更干净。

SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Date day = dateFormat.parse(string);
// add the day
Date dayAfter = new Date(day.getTime() + TimeUnit.DAYS.toMillis(1));