Java LocalDate plusWeeks Method

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to use the plusWeeks() method in Java to add a specified number of weeks to a given date using the LocalDate class.

Import the required package

In order to use the LocalDate class, you need to import the java.time.LocalDate package. Add the following line of code at the top of your DateDemo.java file.

import java.time.LocalDate;

Define the main method

Define the main method in your DateDemo.java file.

public static void main(String[] args){
    // Add code here
}

Create a LocalDate object

Create a LocalDate object with the date you want to add weeks to.

LocalDate localDate = LocalDate.of(2021, 12, 31);

Print the initial date

Print the initial date using the System.out.println() method.

System.out.println("Initial date: " + localDate);

Add weeks to the date using the plusWeeks() method

Use the plusWeeks() method to add a specified number of weeks to the localDate object and store the result in the localDate object.

localDate = localDate.plusWeeks(2);

Print the updated date

Print the updated date using the System.out.println() method.

System.out.println("Updated date: " + localDate);

Compile and run the program

Compile the program using the following command in the terminal:

javac DateDemo.java

Run the program using the following command:

java DateDemo

Update date with current date

Create a LocalDate object to represent the current date.

LocalDate currentDate = LocalDate.now();

Print the updated date

Use the plusWeeks() method to add 5 weeks to the current date and print the updated date.

currentDate = currentDate.plusWeeks(5);
System.out.println("New date: " + currentDate);

Summary

Congratulations! You have successfully learned how to use the plusWeeks() method in Java to add a specified number of weeks to a given date using the LocalDate class. This feature can be useful when calculating dates in the future or past based on specific requirements.

Other Java Tutorials you may like