Java中的 Period withMonths() 方法和示例
Period 类的withMonths()方法用于获取具有指定月数的周期。这个月数作为整数值作为参数传递。
句法:
public Period withMonths(int numberOfMonths)
参数:此方法接受参数numberOfMonths ,该参数是此期间要更改的月数。
返回:此函数返回一个以作为参数传递的月数的Period 。
下面是 Period.withMonths() 方法的实现:
示例 1:
// 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));
}
}
输出:
Period: P1Y2M21D
New Period: P1Y5M21D
示例 2:
// 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));
}
}
输出:
Period: P-1Y-2M-21D
New Period: P-1Y-5M-21D
参考: https://docs.oracle.com/javase/9/docs/api/ Java/time/Period.html#withMonths-int-