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

如何将此日期增加一天?


当前回答

long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);

这将从oldDate中获取自epoch以来的毫秒数,并添加1天的毫秒数,然后使用Date()公共构造函数使用新值创建一个日期。这种方法允许你增加1天,或任何小时/分钟的数量,而不仅仅是一整天。

其他回答

试试这个方法:

public static Date addDay(int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, day);
        return calendar.getTime();
}

自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));

在Java 8中简单的方法是:

Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))

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

 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.util.Date开始/结束。

一些方法:

使用SimpleDateFormat转换为字符串并返回:这是一种效率低下的解决方案。 转换为LocalDate:您将丢失任何时间信息。 转换为LocalDateTime:这涉及更多步骤,您需要考虑时区。 使用Date.getTime()转换为epoch:这很有效,但你是用毫秒计算的。

考虑使用java.time.Instant:

Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);