Period withMonths() method in Java with Examples
Last Updated :
28 Nov, 2018
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:
import java.time.Period;
class GFG {
public static void main(String[] args)
{
String period = "P1Y2M21D" ;
Period p = Period.parse(period);
System.out.println( "Period: " + p);
int numberOfMonths = 5 ;
System.out.println( "New Period: "
+ p.withMonths(numberOfMonths));
}
}
|
Output:
Period: P1Y2M21D
New Period: P1Y5M21D
Example 2:
import java.time.Period;
class GFG {
public static void main(String[] args)
{
String period = "-P1Y2M21D" ;
Period p = Period.parse(period);
System.out.println( "Period: " + p);
int numberOfMonths = - 5 ;
System.out.println( "New Period: "
+ p.withMonths(numberOfMonths));
}
}
|
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-
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...