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.
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.
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 in your DateDemo.java
file.
public static void main(String[] args){
// Add code here
}
Create a LocalDate
object with the date you want to add weeks to.
LocalDate localDate = LocalDate.of(2021, 12, 31);
Print the initial date using the System.out.println()
method.
System.out.println("Initial date: " + localDate);
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 using the System.out.println()
method.
System.out.println("Updated date: " + localDate);
Compile the program using the following command in the terminal:
javac DateDemo.java
Run the program using the following command:
java DateDemo
Create a LocalDate
object to represent the current date.
LocalDate currentDate = LocalDate.now();
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);
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.