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 Check the Connectivity of Graph Using BFS
Hướng dẫn Java Design Pattern – Memento
Spring Boot - File Handling
Java Program to Implement Suffix Tree
Java Program to Implement Hash Tables Chaining with Binary Trees
Guide to @ConfigurationProperties in Spring Boot
Java Program to Solve any Linear Equation in One Variable
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
Java Program to Implement Skip List
Java Program to Represent Graph Using Adjacency List
Guide to the Java ArrayList
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Write/Read cookies using HTTP and Read a file from the internet
HashSet trong java
Java Program to Implement AVL Tree
Introduction to Thread Pools in Java
Java Program to Find Hamiltonian Cycle in an UnWeighted Graph
Java program to Implement Tree Set
A Guide to LinkedHashMap in Java
Java Program to Implement Hash Tables with Linear Probing
Retrieve User Information in Spring Security
Guide to Mustache with Spring Boot
Từ khóa this và super trong Java
Using Optional with Jackson
Java Program to Implement Double Ended Queue
Java 8 Collectors toMap
A Guide to WatchService in Java NIO2
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
Using JWT with Spring Security OAuth (legacy stack)
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Serialize Only Fields that meet a Custom Criteria with Jackson