Open In App

Period getMonths() method in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

The getMonths() method of Period class in Java is used to get the number of months in this current period with which it is used.

Syntax:

public int getMonths()

Parameters: This method does not accepts any parameter.

Return Value: This function returns the number of months in the given period.

Note: There is difference between 12 months and 1 year.

Below programs illustrate the above method:

Program 1:




// Java code to show the function getMonths()
// to get number of months from given period
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodDemo {
  
    // Function to get number of months of given period
    static void getNumberOfDays(int year, int months, int days)
    {
        Period period = Period.of(year, months, days);
        System.out.println(period.getMonths());
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        int year = 0;
        int months = 10;
        int days = 365;
  
        getNumberOfDays(year, months, days);
    }
}


Output:

10

Program 2: This will not convert 13 months to year.




// Java code to show the function getMonths()
// to get number of months from given period
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodDemo {
  
    // Function to get number of months of given period
    static void getNumberOfDays(int year, int months, int days)
    {
        Period period = Period.of(year, months, days);
        System.out.println(period.getMonths());
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        int year = 1;
        int months = 13;
        int days = 36;
  
        getNumberOfDays(year, months, days);
    }
}


Output:

13


Last Updated : 27 Nov, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads