Java Clock Class - java.time.Clock With Examples

Java Clock class is part of Date Time API. Java Clock class is used to get the current instance, date and time with the time zone.

Java Clock Class

  1. Java Clock class is in java.time package.
  2. Java Clock is an abstract class, so we can’t instantiate it. However it contains several static methods to get it’s instance.
  3. Java Clock class usage is optional, because most of the Date API classes has now() method. It’s main purpose is to allow alternate clocks to be plugged in as and when required. For example in Spring Dependency Injection.

    Best practice is to pass a Clock as argument into method that requires the current instant.
  4. Clock can be used instead of System.currentTimeMillis() and TimeZone.getDefault().
  5. Java provides four implementations of Clock – FixedClock, OffsetClock, SystemClock and TickClock. They are part of Clock class and there are static methods that return these Clock implementations.
  6. java-Clock-class-implementations

Java Clock Methods

Let’s look into Clock class static methods and their usage.

systemDefaultZone()

Clock systemDefaultZone() method returns the Clock instance with system default time zone.

instant()

This method returns the current instant of the clock.

systemUTC()

This method returns the Clock instance with UTC time zone.

system(ZoneId zone)

This method is used to get the Clock instance with specified time zone.

millis()

This method returns the current milliseconds of the instance. It’s equivalent to System.currentTimeMillis().

offset(Clock baseClock, Duration offsetDuration)

This method is used to get a Clock with instance added to the given base clock. We can used it to simulate future and past time testing.

tick(Clock baseClock, Duration tickDuration)

This method returns Clock that returns instants from the specified base clock truncated to the nearest occurrence of the specified duration. Let’s see it’s usage with an example code snippet.

Output of above code snippet:

Notice the usage of TickClock and SystemClock instances.

fixed(Instant fixedInstant, ZoneId zone)

This method returns a Clock that always returns the same instant.

Output:

That’s all for Java Clock class usage with examples.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: