Java LocalDate plusMonths Method

JavaBeginner
Practice Now

Introduction

In this lab, we are going to learn about the Java's LocalDate plusMonths() method, which can be used to add months to a date and return a new LocalDate.

Create a new Java file

Create a new Java file named DateDemo.java in the ~/project directory using the following command:

touch ~/project/DateDemo.java

Import LocalDate Class

Import the LocalDate class by adding the following line of code at the top of the file.

import java.time.LocalDate;

Create a LocalDate Object

Create a new LocalDate object and set it to a specific date YYYY-MM-DD format. Here's an example that sets the date to October 21, 2016:

LocalDate localDate = LocalDate.of(2016, 10, 21);

Add Months using plusMonths()

Use the plusMonths() method to add the specified number of months to the date. The method takes a long argument that represents the number of months to add.

localDate = localDate.plusMonths(2);

This adds 2 months to the localDate object and stores the new LocalDate object in the same reference variable.

Finally, print the date to verify that it has been updated.

System.out.println(localDate);

Compile and Run the Code

Use the following command to compile the code:

javac ~/project/DateDemo.java

Use the following command to run the code:

java DateDemo

Add Months to Current Date

You can also add months to the current date using the LocalDate.now() method, which returns the current date. Here's an example that adds 2 months to the current date:

LocalDate localDate = LocalDate.now();
System.out.println(localDate);
localDate = localDate.plusMonths(2);
System.out.println("New date : "+localDate);

Compile and Run the Code

Use the following command to compile the code:

javac ~/project/DateDemo.java

Use the following command to run the code:

java DateDemo

Summary

In this lab, we learned to use the plusMonths() method of the LocalDate class in Java to add months to a date. We learned that the method takes a long argument that represents the number of months to add and returns a new LocalDate object with the specified number of months added. We also learned to create a new LocalDate object, add months to a specific date, and add months to the current date.