How to find Date after 1 week in java 8?


The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay, Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.

Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system.

The now() method of this class obtains the current date from the system clock.

The plus() method of the LocalDate class accepts a long value representing the amount to add and an object of the interface TemporalAmount representing the unit to add and, adds the amount specified to the date of the current LocalDate object and returns it.

Java provides a predefined enum named ChronoUnit which implements the TemporalUnit interface, this provides a set of date periods units. Such as centuries , Days, Decades, eras, hours, minutes, months etc.

To get the date after one week retrieve the current date using the now() method, add a week to it using the plus method by passing 1 and ChronoUnit.WEEKS as parameters to it.

Example

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class CurentTime {
   public static void main(String args[]) {
      //Getting the current Date value
      LocalDate currentDate = LocalDate.now();
      System.out.println("Current date: "+currentDate);
      //Adding one week to the current date
      LocalDate result = currentDate.plus(1, ChronoUnit.WEEKS);
      System.out.println("Day after one week: "+result);
   }
}

Output

Current date: 2019-07-25
Day after one week: 2019-08-01
raja
Published on 07-Aug-2019 14:46:58
Advertisements