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

前端 未结 28 1768

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

How can I increment this date by one day?

相关标签:
28条回答
  • 2020-11-21 07:06

    Construct a Calendar object and use the method add(Calendar.DATE, 1);

    0 讨论(0)
  • 2020-11-21 07:06

    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); 
    }
    
    0 讨论(0)
  • 2020-11-21 07:07
    Date newDate = new Date();
    newDate.setDate(newDate.getDate()+1);
    System.out.println(newDate);
    
    0 讨论(0)
  • 2020-11-21 07:09

    I prefer to use DateUtils from Apache. Check this http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html. It is handy especially when you have to use it multiple places in your project and would not want to write your one liner method for this.

    The API says:

    addDays(Date date, int amount) : Adds a number of days to a date returning a new object.

    Note that it returns a new Date object and does not make changes to the previous one itself.

    0 讨论(0)
  • 2020-11-21 07:09
    long timeadj = 24*60*60*1000;
    Date newDate = new Date (oldDate.getTime ()+timeadj);
    

    This takes the number of milliseconds since epoch from oldDate and adds 1 day worth of milliseconds then uses the Date() public constructor to create a date using the new value. This method allows you to add 1 day, or any number of hours/minutes, not only whole days.

    0 讨论(0)
  • 2020-11-21 07:11

    java.time

    On Java 8 and later, the java.time package makes this pretty much automatic. (Tutorial)

    Assuming String input and output:

    import java.time.LocalDate;
    
    public class DateIncrementer {
      static public String addOneDay(String date) {
        return LocalDate.parse(date).plusDays(1).toString();
      }
    }
    
    0 讨论(0)
提交回复
热议问题