Tuesday, November 18, 2025
HomeLanguagesJavaPeriod getYears() method in Java with Examples

Period getYears() method in Java with Examples

The getYears() method of Period in Java is used to get the amount of years of this period with which it is used. Note: 15 months is not equal to 1 years and 3 months. Syntax:

public List getYears()

Parameters: This method does not accepts any parameter. Returns: This method returns the amounts of years in this current period. Below programs illustrate the above method: Program 1: 

Java




// Java code to show the function getYears()
// to get the number of years in the period
import java.time.Period;
import java.time.temporal.ChronoUnit;
 
public class PeriodDemo {
 
    // Function to get the number of years
    static void getNumberOfDays(int year, int months, int days)
    {
        Period period = Period.of(year, months, days);
        System.out.println(period.getYears());
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int year = 12;
        int months = 3;
        int days = 31;
 
        getNumberOfDays(year, months, days);
    }
}


Output:

12

Program 2: 

Java




// Java code to show the function getYears()
// to get the number of years in the period
import java.time.Period;
import java.time.temporal.ChronoUnit;
 
public class PeriodDemo {
 
    // Function to get the number of years
    static void getNumberOfDays(int year, int months, int days)
    {
        Period period = Period.of(year, months, days);
        System.out.println(period.getYears());
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int year = -12;
        int months = 3;
        int days = 31;
 
        getNumberOfDays(year, months, days);
    }
}


Output:

-12

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#getYears–

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32402 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6772 POSTS0 COMMENTS
Nicole Veronica
11921 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11992 POSTS0 COMMENTS
Shaida Kate Naidoo
6899 POSTS0 COMMENTS
Ted Musemwa
7156 POSTS0 COMMENTS
Thapelo Manthata
6852 POSTS0 COMMENTS
Umr Jansen
6845 POSTS0 COMMENTS