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());
廣告