What is Period.minusDays() in Java?

Overview

The minusDays() method is defined in the Period class. It is used to subtract the specified number of days from the Period instance. The months and years units are unaffected.

Importing Period class

The Period class is defined in the java.time package. To import the Period class check the following import statement.

import java.time.Period;

Syntax

Let’s view the syntax of the function:

public Period minusDays(long daysToSubtract)

Parameters

long daysToSubtract: The number of days to subtract. Can be positive or negative.

Return value

This method returns a new instance of the Period class with the number of days subtracted.

Code

Let’s have a look at the working of the function:

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 days to subtract
int daysToSubtract = 3;
// New Period object after the subtraction
Period newPeriod = basePeriod.minusDays(daysToSubtract);
System.out.printf("%s - %s days = %s", basePeriod, daysToSubtract, newPeriod);
System.out.println();
}
}

In the code above, we subtracted days from the basePeriod object with the help of the minusDays() method and printed the new object to the console.