期间类的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-
相关用法
- Java Period between()用法及代码示例
- Java Period of()用法及代码示例
- Java Period from()用法及代码示例
- Java Period get()用法及代码示例
- Java Period plus()用法及代码示例
- Java Period minusDays()用法及代码示例
- Java Period minus()用法及代码示例
- Java Period ofMonths()用法及代码示例
- Java Period ofDays()用法及代码示例
- Java Period parse()用法及代码示例
- Java Period isZero()用法及代码示例
- Java Period minusMonths()用法及代码示例
- Java Period getYears()用法及代码示例
- Java Period normalized()用法及代码示例
- Java Period negated()用法及代码示例
注:本文由纯净天空筛选整理自barykrg大神的英文原创作品 Period withMonths() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。