Guide to the Java Clock Class

1. Overview

In this tutorial, we’re going to look into the Java Clock class from the java.time package. We’ll explain what the Clock class is and how we can use it.

2. The Clock Class

Clock was added in Java 8 and provides access to an instant in time using the best available system clock, and to be used as a time provider which can be effectively stubbed for testing purposes.

The current date and time depend on the time zone and, for globalized applications, a time provider is necessary to ensure that the date and time are created with the correct time zone.

This class helps us to test that our code changes work with different time zones or – when using a fixed clock –  that time doesn’t affect our code.

The Clock class is abstract, so we cannot create an instance of it. The following factory methods can be used:

  • offset(Clock, Duration) – returns a clock that is offset by the specified Duration. The main use case for this is to simulate running in the future or the past
  • systemUTC() –  returns a clock representing the UTC time zone
  • fixed(Instant, ZoneId) –  always returns the same Instant. The leading use case for this is in testing, where the fixed clock ensures that tests are not dependent on the current clock

We’re going to look into most of the methods available in the Clock class.

2.1. instant()

This method returns an instant representing the current instant defined by the clock:

Clock clock = Clock.systemDefaultZone();
Instant instant = clock.instant();
System.out.println(instant);

will produce:

2018-04-07T03:59:35.555Z

2.2. systemUTC()

This method returns a Clock object representing the current instant in the UTC zone:

Clock clock = Clock.systemUTC();
System.out.println("UTC time :: " + clock.instant());

will produce:

UTC time :: 2018-04-04T17:40:12.353Z

2.3. system()

This static method returns the Clock object for the timezone identified by the given time zone id:

Clock clock = Clock.system(ZoneId.of("Asia/HoChiMinh"));
System.out.println(clock.instant());

will produce:

2018-04-04T18:00:31.376Z

2.4. systemDefaultZone()

This static method returns a Clock object representing the current instant and using the default time zone of the system it’s running on:

Clock clock = Clock.systemDefaultZone();
System.out.println(clock);

The above lines produce the following result (assuming our default time zone is “Asia/HoChiMinh”):

SystemClock[Asia/HoChiMinh]

We can achieve the same behavior by passing ZoneId.systemDefault():

Clock clock = Clock.system(ZoneId.systemDefault());

2.5. millis()

This method returns the current instant of the clock in milliseconds. It’s provided to allow the use of the clock in high-performance use cases where the creation of an object would be unacceptable. This method can be used in places where we’d otherwise have used System.currentTimeInMillis():

Clock clock = Clock.systemDefaultZone();
System.out.println(clock.millis());

will produce:

1523104441258

2.6. offset()

This static method returns an instant from the specified base clock with the specified duration added.

If the duration is negative, then the resulting clock instant will be earlier than the given base clock.

Using offset, we can get instants in the past and future of the given base clock. If we pass a zero duration then we’ll get the same clock as given base clock:

Clock baseClock = Clock.systemDefaultZone();

// result clock will be later than baseClock
Clock clock = Clock.offset(baseClock, Duration.ofHours(72));
System.out.println(clock5.instant());

// result clock will be same as baseClock                           
clock = Clock.offset(baseClock, Duration.ZERO);
System.out.println(clock.instant());

// result clock will be earlier than baseClock            
clock = Clock.offset(baseClock, Duration.ofHours(-72));
System.out.println(clock.instant());

will produce:

2018-04-10T13:24:07.347Z
2018-04-07T13:24:07.348Z
2018-04-04T13:24:07.348Z

2.7. tick()

This static method returns instants from the specified clock rounded to the nearest occurrence of the specified duration. The specified clock duration must be positive:

Clock clockDefaultZone = Clock.systemDefaultZone();
Clock clocktick = Clock.tick(clockDefaultZone, Duration.ofSeconds(30));

System.out.println("Clock Default Zone: " + clockDefaultZone.instant());
System.out.println("Clock tick: " + clocktick.instant());

will produce:

Clock Default Zone: 2018-04-07T16:42:05.473Z
Clock tick: 2018-04-07T16:42:00Z

2.8. tickSeconds()

This static method returns the current instant ticking in whole seconds for the given time zone. This clock will always have the nano-of-second field set to zero:

ZoneId zoneId = ZoneId.of("Asia/HoChiMinh");
Clock clock = Clock.tickSeconds(zoneId);
System.out.println(clock.instant());

will produce:

2018-04-07T17:40:23Z

The same can be achieved by using tick():

Clock clock = Clock.tick(Clock.system(ZoneId.of("Asia/HoChiMinh")), Duration.ofSeconds(1));

2.9. tickMinutes()

This static method returns the clock instant ticking in whole minutes for the specified timezone. This clock will always have the nano-of-second and second-of-minute fields set to zero:

ZoneId zoneId = ZoneId.of("Asia/HoChiMinh");
Clock clock = Clock.tickMinutes(zoneId);
System.out.println(clock.instant());

will produce:

2018-04-07T17:26:00Z

The same can be achieved by using tick():

Clock clock = Clock.tick(Clock.system(ZoneId.of("Asia/HoChiMinh")), Duration.ofMinutes(1));

2.10. withZone()

This method returns a copy of this clock with a different time zone.

If we have a clock instance for a specific time zone, we can make a copy of that clock for different time zone:

ZoneId zoneSingapore = ZoneId.of("Asia/Singapore");  
Clock clockSingapore = Clock.system(zoneSingapore); 
System.out.println(clockSingapore.instant());

ZoneId zoneCalcutta = ZoneId.of("Asia/HoChiMinh");
Clock clockCalcutta = clockSingapore.withZone(zoneCalcutta);
System.out.println(clockCalcutta.instant());

will produce:

2018-04-07T17:55:43.035Z
2018-04-07T17:55:43.035Z

2.11. getZone()

This method returns the time zone of the given Clock.

Clock clock = Clock.systemDefaultZone();
ZoneId zone = clock.getZone();
System.out.println(zone.getId());

will produce:

Asia/HoChiMinh

2.12. fixed()

This method returns a clock that always returns the same instant. The main use case for this method is in testing, where the fixed clock ensures that tests are not dependent on the current clock.

Clock fixedClock = Clock.fixed(Instant.parse("2018-04-29T10:15:30.00Z"),
ZoneId.of("Asia/HoChiMinh"));
System.out.println(fixedClock);

will produce:

FixedClock[2018-04-29T10:15:30Z,Asia/HoChiMinh]

3. Conclusion

In this article, we dove into the Java Clock class and the different ways we can use it with the available methods.

As always, the code examples are available over on GitHub.

Related posts:

Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
Java – Delete a File
Java Program to Implement Park-Miller Random Number Generation Algorithm
Prevent Cross-Site Scripting (XSS) in a Spring Application
Java Program to Implement Affine Cipher
Java Program to Find the Longest Path in a DAG
Java Program for Douglas-Peucker Algorithm Implementation
Converting Between an Array and a Set in Java
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Implement Fibonacci Heap
Netflix Archaius with Various Database Configurations
Introduction to Spring MVC HandlerInterceptor
Lập trình đa luồng với CompletableFuture trong Java 8
Các nguyên lý thiết kế hướng đối tượng – SOLID
HTTP Authentification and CGI/Servlet
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
A Comparison Between Spring and Spring Boot
Spring Boot - Admin Server
Guide to java.util.concurrent.Future
Spring Boot with Multiple SQL Import Files
Java Program to Implement ArrayList API
Transaction Propagation and Isolation in Spring @Transactional
Lớp lồng nhau trong java (Java inner class)
Java Program to Represent Graph Using Incidence List
Spring MVC Custom Validation
Service Registration with Eureka
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
New Features in Java 8
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Java Program to implement Dynamic Array
Java Program to Implement Radix Sort