期間類的withYears()方法用於獲取指定年數的期間。該年數作為參數傳遞為整數值。
用法:
public Period withYears(int numberOfYears)
參數:此方法接受參數numberOfYears,它是此期間要更改的年數。
返回值:此函數返回以傳遞的年數作為參數的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-
相關用法
- Java Period of()用法及代碼示例
- Java Period between()用法及代碼示例
- 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 withYears() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。