Java中的Clock tick()方法
可以使用tick()
Java中Clock类中的方法在所需的时间范围内舍入基本时钟的瞬间。此方法需要两个参数,即基本时钟和滴答的持续时间。同样,返回在所需持续时间内四舍五入的基本时钟时刻。
演示此的程序如下所示-
示例
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());