Java 中 Period 的 withDays() 方法


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

輸出

The Period is: P5Y7M15D
The Period with days altered to 3 is: P5Y7M3D

現在讓我們理解上述程式。

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

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

更新日期:30-7-2019

173 次瀏覽

啟動你的 事業

透過完成課程獲得認證

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