Java Period withYears()方法及示例
Period类 的 withYears() 方法是用来获得一个具有指定年数的周期。该年数作为参数以整数形式传递。
语法
public Period withYears(int numberOfYears)
参数: 该方法接受一个参数numberOfYears,它是这个Period中要改变的年数。
返回: 该函数返回一个带有作为参数的年数的Period。
下面是Period.withYears()方法的实现。
例子 1:
// Java code to demonstrate withYears() method
import java.time.Period;
class GFG {
public static void main(String[] args)
{
// Get the String to be withYearsd
String period = "P1Y2M21D";
// Parse the String into Period
Period p = Period.parse(period);
System.out.println("Period: " + p);
// Get the number of years
int numberOfYears = 5;
// Change the numberOfYears of this Period
// using withYears() method
System.out.println("New Period: "
+ p.withYears(numberOfYears));
}
}
输出:
Period: P1Y2M21D
New Period: P5Y2M21D
例2:
// Java code to demonstrate withYears() method
import java.time.Period;
class GFG {
public static void main(String[] args)
{
// Get the String to be withYearsd
String period = "-P1Y2M21D";
// Parse the String into Period
Period p = Period.parse(period);
System.out.println("Period: " + p);
// Get the number of years
int numberOfYears = -5;
// Change the numberOfYears of this Period
// using withYears() method
System.out.println("New Period: "
+ p.withYears(numberOfYears));
}
}
输出:
Period: P-1Y-2M-21D
New Period: P-5Y-2M-21D
参考资料: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#withYears-int-