可以使用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());