Java 中 LocalDateTime 的 withYear() 方法


在 Java 中的 LocalDateTime 類的 withYear() 方法用於設定一個不可變副本,其中更改了所需的年。該方法需要一個引數,即在 LocalDateTime 中要設定的年,並返回所需的年已更改的 LocalDateTime。

一個演示此內容的程式如下所示 -

示例

 線上演示

import java.time.*;
public class Main {
   public static void main(String[] args) {
      LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
      System.out.println("The LocalDateTime is: " + ldt1);
      LocalDateTime ldt2 = ldt1.withYear(2020);
      System.out.println("The LocalDateTime with year altered is: " + ldt2);
   }
}

輸出

The LocalDateTime is: 2019-02-18T23:15:30
The LocalDateTime with year altered is: 2020-02-18T23:15:30

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

首先顯示 LocalDateTime。然後使用 withYear() 方法將 LocalDateTime 的年更改為 2020 年並顯示。一個演示此內容的程式碼片段如下所示 -

LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
System.out.println("The LocalDateTime is: " + ldt1);
LocalDateTime ldt2 = ldt1.withYear(2020);
System.out.println("The LocalDateTime with year altered is: " + ldt2);

更新於: 2019-07-30

101 檢視

啟動您的職業生涯

完成課程以獲得認證

開始
廣告