How can I increment a date by one day in Java?

2018-12-31 01:23发布

I'm working with a date in this format: yyyy-mm-dd.

How can I increment this date by one day?

标签: java date
25条回答
美炸的是我
2楼-- · 2018-12-31 01:55
Date newDate = new Date();
newDate.setDate(newDate.getDate()+1);
System.out.println(newDate);
查看更多
步步皆殇っ
3楼-- · 2018-12-31 02:00

Just pass date in String and number of next days

 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;

}
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 02:00

Java does appear to be well behind the eight-ball compared to C#. This utility method shows the way to do in Java SE 6 using the Calendar.add method (presumably the only easy way).

public class DateUtil
{
    public static Date addDays(Date date, int days)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days); //minus number would decrement the days
        return cal.getTime();
    }
}

To add one day, per the question asked, call it as follows:

String sourceDate = "2012-02-29";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, 1);
查看更多
余欢
5楼-- · 2018-12-31 02:00

Take a look at Joda-Time (http://joda-time.sourceforge.net/).

DateTimeFormatter parser = ISODateTimeFormat.date();

DateTime date = parser.parseDateTime(dateString);

String nextDay = parser.print(date.plusDays(1));
查看更多
伤终究还是伤i
6楼-- · 2018-12-31 02:01

Use the DateFormat API to convert the String into a Date object, then use the Calendar API to add one day. Let me know if you want specific code examples, and I can update my answer.

查看更多
泪湿衣
7楼-- · 2018-12-31 02:01

If you are using Java 8, java.time.LocalDate and java.time.format.DateTimeFormatter can make this work quite simple.

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); 
}
查看更多
登录 后发表回答