Java Period getYears()

In this guide, you will learn about the Period getYears() method in Java programming and how to use it with an example.

1. Period getYears() Method Overview

Definition:

The Period.getYears() method in Java belongs to the java.time.Period class. It is used to obtain the amount of years in this period. The Period class represents a quantity of time in terms of years, months, and days and is mainly used for date-based amounts of time in the ISO-8601 calendar system.

Syntax:

public int getYears()

Parameters:

- The method does not take any parameters.

Key Points:

- The getYears() method returns the year part of the Period, which can be negative.

- The Period class is a part of the java.time package, which was introduced in Java 8 to provide a comprehensive and well-structured API for date and time manipulation.

- The Period object is immutable and thread-safe, providing safety in multithreaded environments.

2. Period getYears() Method Example

import java.time.Period;

public class PeriodGetYearsExample {
    public static void main(String[] args) {
        // Create a Period of 2 years, 3 months, and 5 days
        Period period = Period.of(2, 3, 5);

        // Get the year part of the period
        int years = period.getYears();

        // Print the number of years
        System.out.println("Number of years in the period: " + years);

        // Create a Period with a negative number of years
        Period negativePeriod = Period.of(-1, 0, 0);

        // Get the year part of the negative period
        int negativeYears = negativePeriod.getYears();

        // Print the number of years in the negative period
        System.out.println("Number of years in the negative period: " + negativeYears);
    }
}

Output:

Number of years in the period: 2
Number of years in the negative period: -1

Explanation:

In this example, two Period objects are created – one with positive years and the other with negative years. The getYears() method is utilized to obtain the year part of these periods. 

  • The first Period object, period, is constructed with 2 years, 3 months, and 5 days, resulting in the getYears() method returning 2
  • The second Period object, negativePeriod, is constructed with -1 year, hence getYears() returns -1.

Comments