Java 中的 LocalDate withYear() 方法


Java 中 LocalDate 類的 withYear() 方法用於建立 LocalDate 的不可變副本,其中年的值已根據需要進行修改。此方法需要一個引數,即要在 LocalDate 中設定的年份,並返回年份經過修改後的 LocalDate。

以下程式對此進行了演示:

示例

 即時演示

import java.time.*;
public class Main {
   public static void main(String[] args) {
      LocalDate ld1 = LocalDate.parse("2019-02-15");
      System.out.println("The LocalDate is: " + ld1);
      LocalDate ld2 = ld1.withYear(2015);
      System.out.println("The LocalDate with year altered is: " + ld2);
   }
}

輸出

The LocalDate is: 2019-02-15
The LocalDate with year altered is: 2015-02-15

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

首先顯示 LocalDate。然後使用 withYear() 方法顯示年份已修改為 2015 的 LocalDate。演示此操作的程式碼片段如下:

LocalDate ld1 = LocalDate.parse("2019-02-15");
System.out.println("The LocalDate is: " + ld1);
LocalDate ld2 = ld1.withYear(2015);
System.out.println("The LocalDate with year altered is: " + ld2);

更新於:2019 年 7 月 30 日

130 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.