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 次浏览

开启你的 职业

完成课程即可获得认证

开始学习
广告