Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
minusmonths
period

What is Period.minusMonths() in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

minusMonths() is an instance method defined in the Period class. It is used to subtract the specified number of months from the Period instance. The days 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;
Importing Period class

Syntax

The syntax of the function is as follows:

public Period minusMonths(long monthsToSubtract)
minusMonths syntax in Java

Parameters

long monthsToSubtract: The number of months to subtract. Can be positive or negative.

Return value

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

Code

Let’s have a look at the working of this 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 months to subtract
        int monthsToSubtract = 3;

        // New Period object after the subtraction
        Period newPeriod = basePeriod.minusMonths(monthsToSubtract);
        System.out.printf("%s - %s months = %s", basePeriod, monthsToSubtract, newPeriod);
        System.out.println();
    }
}

In the code above, we subtract 3 months from the basePeriod object with the help of the minusMonths() method and print the new object to the console.

RELATED TAGS

java
communitycreator
minusmonths
period

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring