Java 中的 Period withYears() 方法


使用 Java 中 Period 類的 withYears() 方法可以獲得一個不變的 Period 副本,其中包含所需數量的年。此方法需要一個引數,即 Period 中的年數,並且它返回包含所需數量的年的 Period。

下面是一個展示此功能的程式

示例

 互動演示

import java.time.Period;
public class Demo {
   public static void main(String[] args) {
      String period = "P5Y7M15D";
      Period p1 = Period.parse(period);
      System.out.println("The Period is: " + p1);
      Period p2 = p1.withYears(3);
      System.out.println("The Period with years altered to 3 is: " + p2);
   }
}

輸出

The Period is: P5Y7M15D
The Period with years altered to 3 is: P3Y7M15D

下面讓我們瞭解一下上述程式。

首先顯示 Period。然後使用 withYears() 方法顯示將年數更改為 3 的 Period。演示它的程式碼片段如下

String period = "P5Y7M15D";
Period p1 = Period.parse(period);
System.out.println("The Period is: " + p1);
Period p2 = p1.withYears(3);
System.out.println("The Period with years altered to 3 is: " + p2);

更新於: 2019-07-30

131 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.