即時 truncatedTo() 方法在 Java 中


可以在 Java 中使用 Instant 類的 truncatedTo() 方法獲取不可變的截斷 Instant。此方法需要一個引數,即截斷 Instant 的 TemporalUnit,並返回不可變的截斷 Instant。

演示此方法的程式如下 −

示例

 即時演示

import java.time.*;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      Instant instant = Instant.now();
      System.out.println("The current instant is: " + instant);
      Instant truncatedInstant = instant.truncatedTo(ChronoUnit.MINUTES);
      System.out.println("The truncated instant is: " + truncatedInstant);
   }
}

輸出

The current instant is: 2019-02-13T08:49:09.188Z
The truncated instant is: 2019-02-13T08:49:00Z

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

首先顯示當前 Instant。然後使用 truncatedTo() 方法獲取不可變的截斷 Instant,並將其顯示。演示此方法的程式碼片段如下 −

Instant instant = Instant.now();
System.out.println("The current instant is: " + instant);
Instant truncatedInstant = instant.truncatedTo(ChronoUnit.MINUTES);
System.out.println("The truncated instant is: " + truncatedInstant);

更新日期:2019 年 7 月 30 日

743 次瀏覽

開啟你的 職業

完成課程並獲得認證

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