Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Period ofMonths() method in Java with Examples

  • Last Updated : 28 Nov, 2018

The ofMonths() method of Period Class is used to obtain a period from given number of Months as parameter. This parameter is accepted in the form of integer. This method returns a Period with the given number of months.

Syntax:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

public static Period ofMonths(int numberOfMonths)

Parameters: This method accepts a single parameter numberOfMonths which is the number of Months to be parsed into an Period object.

Returns: This function returns the period which is the Period object parsed with the given number of Months.



Below is the implementation of Period.ofMonths() method:

Example 1:




// Java code to demonstrate ofMonths() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the number of Months
        int numberOfMonths = 5;
  
        // Parse the numberOfMonths into Period
        // using ofMonths() method
        Period p = Period.ofMonths(numberOfMonths);
  
        System.out.println(p.getYears() + " Years\n"
                           + p.getMonths() + " Months\n"
                           + p.getDays() + " Days");
    }
}
Output:
0 Years
5 Months
0 Days

Example 2:




// Java code to demonstrate ofMonths() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the number of Months
        int numberOfMonths = -5;
  
        // Parse the numberOfMonths into Period
        // using ofMonths() method
        Period p = Period.ofMonths(numberOfMonths);
  
        System.out.println(p.getYears() + " Years\n"
                           + p.getMonths() + " Months\n"
                           + p.getDays() + " Days");
    }
}
Output:
0 Years
-5 Months
0 Days

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#ofMonths-int-




My Personal Notes arrow_drop_up
Recommended Articles
Page :