Java 中的 Clock tick() 方法


可以透過使用 Java 中 Clock 類的 tick() 方法,按所需持續時間對基本時鐘的物件進行舍入。此方法需要兩個引數,即基本時鐘和滴答持續時間。另外,還會返回按所需持續時間舍入的基本時鐘的物件。

演示此過程的一個程式如下 −

示例

 線上示例

import java.time.*;
public class Main {
   public static void main(String[] args) {
      Clock bClock = Clock.systemDefaultZone();
      Instant i = bClock.instant();
      System.out.println("The Instant of the base clock is: " + i);
      Clock c1 = Clock.tick(bClock, Duration.ofSeconds(45));
      System.out.println("Instant of the first clock with duration 45 seconds is: " + c1.instant());
      Clock c2 = Clock.tick(bClock, Duration.ofHours(45));
      System.out.println("Instant of the first clock with duration 45 hours is: " + c2.instant());
      Clock c3 = Clock.tick(bClock, Duration.ofDays(45));
      System.out.println("Instant of the first clock with duration 45 days is: " + c3.instant());
   }
}

輸出

The Instant of the base clock is: 2019-02-06T12:26:22.488Z
Instant of the first clock with duration 45 seconds is: 2019-02-06T12:26:15Z
Instant of the first clock with duration 45 hours is: 2019-02-05T12:00:00Z
Instant of the first clock with duration 45 days is: 2019-01-14T00:00:00Z

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

使用 tick() 方法按所需持續時間對基本時鐘的物件進行舍入。然後,使用 instant() 方法顯示此物件。演示此過程的程式碼段如下 −

Clock bClock = Clock.systemDefaultZone();
Instant i = bClock.instant();
System.out.println("The Instant of the base clock is: " + i);
Clock c1 = Clock.tick(bClock, Duration.ofSeconds(45));
System.out.println("Instant of the first clock with duration 45 seconds is: " + c1.instant());
Clock c2 = Clock.tick(bClock, Duration.ofHours(45));
System.out.println("Instant of the first clock with duration 45 hours is: " + c2.instant());
Clock c3 = Clock.tick(bClock, Duration.ofDays(45));
System.out.println("Instant of the first clock with duration 45 days is: " + c3.instant());

更新於: 2019 年 7 月 30 日

227 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始學習
廣告