Period 中的 minusMonths() 方法在 Java 中


在 Java 中,可以使用 Period 類中的 minusMonths() 方法獲取 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.minusMonths(2);
      System.out.println("The Period after subtracting 2 months is: " + p2);
   }
}

輸出

The Period is: P5Y7M15D
The Period after subtracting 2 months is: P5Y5M15D

現在,讓我們瞭解一下上面的程式。

首先顯示當前週期。然後,使用 minusMonths() 方法獲取 Period 的不可變副本,其中減去 2 個月,並顯示。演示此方法的程式碼片段如下

String period = "P5Y7M15D";
Period p1 = Period.parse(period);
System.out.println("The Period is: " + p1);
Period p2 = p1.minusMonths(2);
System.out.println("The Period after subtracting 2 months is: " + p2);

更新於: 30-Jul-2019

109 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

入門
廣告
© . All rights reserved.