Friday, September 5, 2025
HomeLanguagesJavaPeriod minusMonths() method in Java with Examples

Period minusMonths() method in Java with Examples

The minusMonths() method of Period class in Java is used to subtract the specified months from given period. This method operates only on MONTHS and does not affect other two YEAR, DAYS.

Syntax:

public Period minusMonths(long monthsToSubtract)

Parameters: This method accepts a single parameter monthsToSubtract which is the number of months to be subtracted from the period.

Return Value: This method returns a Period based on provided period in the input subtracting the specified number of months. It must not be null.

Exceptions: It throws an ArithmeticException. This exception is caught if numeric overflow occurs.

Below programs illustrate the above method:

Program 1:




// Java code to show the function minusMonths()
// to subtract the number of months from given periods
  
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodClass {
  
    // Function to subtract two given periods
    static void subtractMonths(Period p1, int monthstoSubtract)
    {
        System.out.println(p1.minusMonths(monthstoSubtract));
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Defining first period
        int year = 4;
        int months = 11;
        int days = 10;
        Period p1 = Period.of(year, months, days);
  
        int monthstoSubtract = 8;
  
        subtractMonths(p1, monthstoSubtract);
    }
}


Output:

P4Y3M10D

Program 2:




// Java code to show the function minusMonths()
// to subtract the number of months from given periods
  
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodClass {
  
    // Function to subtract two given periods
    static void subtractMonths(Period p1, int monthstoSubtract)
    {
        System.out.println(p1.minusMonths(monthstoSubtract));
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Defining first period
        int year = -4;
        int months = -11;
        int days = -10;
        Period p1 = Period.of(year, months, days);
  
        int monthstoSubtract = -8;
  
        subtractMonths(p1, monthstoSubtract);
    }
}


Output:

P-4Y-3M-10D

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#minusMonths-long-

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11866 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS