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

前端 未结 28 1779

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

提交回复
热议问题