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

前端 未结 28 1771

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

    Since Java 1.5 TimeUnit.DAYS.toMillis(1) looks more clean to me.

    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));
    
    0 讨论(0)
  • 2020-11-21 07:11

    Apache Commons already has this DateUtils.addDays(Date date, int amount) http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html#addDays%28java.util.Date,%20int%29 which you use or you could go with the JodaTime to make it more cleaner.

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

    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.

    0 讨论(0)
  • 2020-11-21 07:15
    startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender
    
    0 讨论(0)
  • 2020-11-21 07:16

    Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.

    Some approaches:

    1. Convert to string and back with SimpleDateFormat: This is an inefficient solution.
    2. Convert to LocalDate: You would lose any time-of-day information.
    3. Convert to LocalDateTime: This involves more steps and you need to worry about timezone.
    4. Convert to epoch with Date.getTime(): This is efficient but you are calculating with milliseconds.

    Consider using java.time.Instant:

    Date _now = new Date();
    Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
    Date _newDate = Date.from(_instant);
    
    0 讨论(0)
  • 2020-11-21 07:17
    Date today = new Date();               
    SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd");            
    Calendar c = Calendar.getInstance();        
    c.add(Calendar.DATE, 1);  // number of days to add      
    String tomorrow = (String)(formattedDate.format(c.getTime()));
    System.out.println("Tomorrows date is " + tomorrow);
    

    This will give tomorrow's date. c.add(...) parameters could be changed from 1 to another number for appropriate increment.

    0 讨论(0)
提交回复
热议问题