What is Period.minusYears() in Java?

minusYears() is an instance method of the Period class, which is used to subtract the specified number of years from the Period instance. The months and days units are not affected by this method.

The minusYears() method is defined in the Period class. The Period class is defined in the java.time package. To import the Period class, we will check the following import statement:

import java.time.Period;

Syntax


public Period minusYears(long yearsToSubtract)

Parameters

  • long yearsToSubtract: This is the number of years that need to be subtracted from the instance. This number can either be positive or negative.

Return value

This method returns a new instance of the Period class, after subtracting a specified number of years from the original ‘Period’ instance.

Code

In the code below, we will subtract three years from the basePeriod object with the help of the minusYears() method. Then, we will 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 object
Period basePeriod = Period.of(numYears, numMonths, numDays);
// number of years to subtract
int yearsToSubtract = 3;
// New Period object after the subtraction
Period newPeriod = basePeriod.minusYears(yearsToSubtract);
System.out.printf("%s - %s years = %s", basePeriod, yearsToSubtract, newPeriod);
System.out.println();
}
}

Free Resources