What is Period.plusMonths() in Java?
plusMonths() is an instance method of the Period class. It is used to add the specified number of months. The years and days units are unaffected.
The plusMonths() method is defined in the Period class. The Period class is defined in the java.time package. Here is how we import the Period class.
import java.time.Period;
Syntax
public Period plusMonths(long monthsToAdd)
Parameters
long monthsToAdd: The number of months to add. It can be positive or negative.
Return value
This method returns a new instance of the Period class with the number of months added.
Code
In the below code, we add three months to the basePeriod object with the help of the plusMonths() method and print the new object to the console.
import java.time.Period;public class Main{public static void main(String[] args) {int numYears = 5;int numMonths = 10;int numDays = 13;// Define a period objectPeriod basePeriod = Period.of(numYears, numMonths, numDays);// number of days to addint monthsToAdd = 3;// New Period object after the additionPeriod newPeriod = basePeriod.plusMonths(monthsToAdd);System.out.printf("%s + %s months = %s", basePeriod, monthsToAdd, newPeriod);System.out.println();}}