Java Period getMonths()

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

1. Period getMonths() Method Overview

Definition:

The Period.getMonths() method in Java is a part of the java.time.Period class. It is used to get the amount of months in this period. Period is primarily used for dealing with a quantity of time in terms of years, months, and days.

Syntax:

public int getMonths()

Parameters:

- The method does not take any parameters.

Key Points:

- The getMonths() method returns the month part of the Period, which may be negative.

- The Period class is included in the java.time package, which was introduced in Java 8 as a comprehensive model for date and time manipulation.

- The Period object is immutable and thread-safe, thus ensuring safe operations across threads.

2. Period getMonths() Method Example

import java.time.Period;

public class PeriodGetMonthsExample {
    public static void main(String[] args) {
        // Create a Period of 1 year, 6 months, and 10 days
        Period period = Period.of(1, 6, 10);

        // Get the month part of the period
        int months = period.getMonths();

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

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

        // Get the month part of the negative period
        int negativeMonths = negativePeriod.getMonths();

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

Output:

Number of months in the period: 6
Number of months in the negative period: -3

Explanation:

In this example, two Period objects are created – one with positive months and the other with negative months. 

The getMonths() method is utilized to obtain the month part of these periods. 

  • The first Period object, period, is constructed with 1 year, 6 months, and 10 days, resulting in the getMonths() method returns 6
  • The second Period object, negativePeriod, is constructed with -3 months, leading to getMonths() returning -3.

Comments