What is Period.minus() in Java?

Overview

minus() is an instance method of the Period class used to subtract the specified Period from the Period object on which the method is called. This method operates individually on the years, months, and days of the Period object. No normalization is performed in this method.

The minus method is defined in the Period class. The Period class is defined in the java.time package. To import the Period class, use the following import statement:

import java.time.Period;

Syntax


public Period minus(TemporalAmount amountToSubtract)

Parameters

  • TemporalAmount amountToSubtract: The amount to subtract from the Period object.

Return value

This method returns a copy of the Period object on which the method is called with the specified period subtracted.

Code

import java.time.Period;
public class Main {
public static void main(String[] args) {
Period period1 = Period.of(4 ,5, 9);
Period period2 = Period.of(4 ,9, 24);
Period diffPeriod = period1.minus(period2);
System.out.printf("%s - %s = %s", period1, period2, diffPeriod);
}
}

Explanation

  • Line 1: We import the Period class.
  • Line 6: We define the first Period object.
  • Line 7: We define the second Period object.
  • Line 9: We subtract the second Period object from the first one using the minus() method.
  • Line 10: We print the period objects and the difference obtained in Line 9.

Free Resources