Wednesday, July 1, 2026
HomeLanguagesJavaPeriod minusYears() method in Java with Examples

Period minusYears() method in Java with Examples

The minusYears() method of Period class in Java is used to subtract the specified years from given period. This functions operates only on YEARS and does not affect other two MONTHS and DAYS.

Syntax:

public Period minusYears(long yearsToSubtract)

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

Returns Value: This method returns a Period based on provided period in the input subtracting the specified number of years. 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 minusYears()
// to subtract the number of years from given period
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodClass {
  
    // Function to subtract two given periods
    static void subtractYears(Period p1, int yearstoSubtract)
    {
  
        System.out.println(p1.minusYears(yearstoSubtract));
    }
  
    // 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 yearstoSubtract = 8;
  
        subtractYears(p1, yearstoSubtract);
    }
}


Output:

P-4Y11M10D

Program 2:




// Java code to show the function minusYears()
// to subtract the number of years from given period
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodClass {
  
    // Function to subtract two given periods
    static void subtractYears(Period p1, int yearstoSubtract)
    {
  
        System.out.println(p1.minusYears(yearstoSubtract));
    }
  
    // 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 yearstoSubtract = -8;
  
        subtractYears(p1, yearstoSubtract);
    }
}


Output:

P12Y11M10D

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

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32517 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6900 POSTS0 COMMENTS
Nicole Veronica
12014 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12110 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6966 POSTS0 COMMENTS