Java 中 Instant plus() 方法


在 Java 中 Instant 類的 plus() 方法可用於獲取不可變副本,其中向 instant 添加了時間單位。此方法需要兩個引數,即要新增到 instant 的時間以及要新增時間的單位。它還返回添加了所需時間單位的 instant 不可變副本。

示範此內容的程式如下 −

示例

 即時演示

import java.time.*;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      Instant i = Instant.now();
      System.out.println("The current instant is: " + i);
      Instant add = i.plus(2, ChronoUnit.HOURS);
      System.out.println("The instant with 2 hours added is: " + add);
   }
}

輸出

The current instant is: 2019-02-13T06:33:27.414Z
The instant with 2 hours added is: 2019-02-13T08:33:27.414Z

現在,讓我們來理解一下以上程式。

首先顯示當前 instant。然後使用 plus() 方法獲取不可變副本,其中添加了 2 小時,並顯示此副本。用於示範此內容的程式碼片段如下 −

Instant i = Instant.now();
System.out.println("The current instant is: " + i);
Instant add = i.plus(2, ChronoUnit.HOURS);
System.out.println("The instant with 2 hours added is: " + add);

更新時間:2019 年 7 月 30 日

2K+ 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始吧
廣告
© . All rights reserved.