Clock tick() Method in Java

Java 8ProgrammingObject Oriented Programming

The instant of the base clock can be rounded off for the required duration using the method tick() in the Clock Class in Java. This method requires two parameters i.e. the base clock and the duration of the tick. Also, the instant of the base clock rounded off for the required duration is returned.

A program that demonstrates this is given as follows −

Example

 Live Demo

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());
   }
}

Output

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

Now let us understand the above program.

The instant of the base clock is rounded off for the required duration using the method tick(). Then this is displayed using instant() method. A code snippet that demonstrates this is as follows −

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());
raja
Published on 13-Mar-2019 15:12:17
Advertisements