Period withMonths() method in Java with Examples

The withMonths() method of Period Class is used to obtain a period with specified number of months. This number of months is passed as the parameter as integer value.

Syntax:

public Period withMonths(int numberOfMonths)

Parameters: This method accepts a parameter numberOfMonths which is the number of months to be changed in this Period.

Returns: This function returns a Period with the number of months passed as the parameter.

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



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to demonstrate withMonths() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the String to be withMonthsd
        String period = "P1Y2M21D";
  
        // Parse the String into Period
        Period p = Period.parse(period);
  
        System.out.println("Period: " + p);
  
        // Get the number of months
        int numberOfMonths = 5;
  
        // Change the numberOfMonths of this Period
        // using withMonths() method
        System.out.println("New Period: "
                           + p.withMonths(numberOfMonths));
    }
}

chevron_right


Output:

Period: P1Y2M21D
New Period: P1Y5M21D

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to demonstrate withMonths() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the String to be withMonthsd
        String period = "-P1Y2M21D";
  
        // Parse the String into Period
        Period p = Period.parse(period);
  
        System.out.println("Period: " + p);
  
        // Get the number of months
        int numberOfMonths = -5;
  
        // Change the numberOfMonths of this Period
        // using withMonths() method
        System.out.println("New Period: "
                           + p.withMonths(numberOfMonths));
    }
}

chevron_right


Output:

Period: P-1Y-2M-21D
New Period: P-1Y-5M-21D

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.