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

前端 未结 28 1858

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:03

    If you are using Java 8, then do it like this.

    LocalDate sourceDate = LocalDate.of(2017, Month.MAY, 27);  // Source Date
    LocalDate destDate = sourceDate.plusDays(1); // Adding a day to source date.
    
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Setting date format
    
    String destDate = destDate.format(formatter));  // End date
    

    If you want to use SimpleDateFormat, then do it like this.

    String sourceDate = "2017-05-27";  // Start date
    
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(sdf.parse(sourceDate)); // parsed date and setting to calendar
    
    calendar.add(Calendar.DATE, 1);  // number of days to add
    String destDate = sdf.format(calendar.getTime());  // End date
    

提交回复
热议问题