While working with Java date and time, we may require to add or subtract weeks from date. For this, Java provides plusWeeks() method to add more weeks to the existing date. In this article, we have a couple of examples to add weeks in current and given date.
Here, we used the now() method of LocalDate class to get the current/today's date and then used plusWeeks() method to add weeks in the current date.
import java.time.LocalDate;
/*
* Code example to add weeks to local date in Java
*/
public class JExercise {
public static void main(String[] args) {
// Current Date
LocalDate localDate = LocalDate.now();
System.out.println("Current Date: "+localDate);
// Add Weeks
LocalDate newLocalDate = localDate.plusWeeks(2);
System.out.println("Date After Adding Weeks: "+newLocalDate);
}
}
Output:
Current Date: 2021-02-19
Date After Adding Weeks: 2021-03-05
To increment a week to a date in Java, we can use the plusWeeks() method by passing 1 as an argument. See the code example.
import java.time.LocalDate;
/*
* Code example to increment a week to date in Java
*/
public class JExercise {
public static void main(String[] args) {
// Current Date
LocalDate localDate = LocalDate.now();
System.out.println("Current Date: "+localDate);
// Add Weeks
LocalDate newLocalDate = localDate.plusWeeks(1);
System.out.println("Date After incrementing a Week: "+newLocalDate);
}
}
Output:
Current Date: 2021-02-19
Date After Adding Weeks: 2021-02-26
We can use the plusWeeks() method to add any number of weeks in the date as we are adding 2 weeks to the week here.
import java.time.LocalDate;
/*
* Code example to add weeks to local date in Java
*/
public class JExercise {
public static void main(String[] args) {
// Some Date
String date = "2012-11-15";
LocalDate localDate = LocalDate.parse(date);
System.out.println("Current Date: "+localDate);
// Add Weeks
LocalDate newLocalDate = localDate.plusWeeks(2);
System.out.println("Date After Adding Weeks: "+newLocalDate);
}
}
Output:
Current Date: 2012-11-15
Date After Adding Weeks: 2012-11-29