Monday, February 16, 2026
HomeLanguagesJavaPeriod ofMonths() method in Java with Examples

Period ofMonths() method in Java with Examples

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:

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-

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS