Java 中的 Period withMonths() 方法


在 Java 中的 Period 類中,使用 withMonths() 方法執行該 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.withMonths(3);
      System.out.println("The Period with months altered to 3 is: " + p2);
   }
}

輸出

The Period is: P5Y7M15D
The Period with months altered to 3 is: P5Y3M15D

現在,讓我們瞭解上述程式。

首先,顯示 Period。然後,使用 withMonths() 方法顯示將月份數更改為 3 的 Period。演示此操作的程式碼片段如下

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

更新於:30-Jul-2019

135 次瀏覽

開啟你的 職業生涯

完成課程以認證

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