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

如何将此日期增加一天?


当前回答

你可以在一行中完成。

例如增加5天

Date newDate = Date.from(Date().toInstant().plus(5, ChronoUnit.DAYS));

减去5天

Date newDate = Date.from(Date().toInstant().minus(5, ChronoUnit.DAYS));

其他回答

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

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

但是这条线增加了一天

cal.add( Calendar.DATE, 1 );

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

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

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

其实很简单。 一天包含86400000毫秒。 所以首先你从系统中通过使用System. currenttimemillis()获得当前时间,单位是millis 添加8000000毫秒,并使用日期类生成以毫秒为单位的日期格式。

例子

String Today = new Date(System.currentTimeMillis()).toString();

今天是2019-05-9

String明天=新的日期(System.currentTimeMillis() + 86400000).toString();

明天将是2019-05-10

最新消息。

字符串后天将是2019-05-11

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

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

 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;

}