skip to content

What is java.time.Clock, how do systemUTC, fixed and offset differ, and why inject one instead of calling Instant.now()?

level: middleimportance: should knowfreq 44%

answer

  1. a replaceable source of now
  2. current instant plus a time-zone
  3. real clock, frozen clock, shifted wrapper
  4. pass it in, avoid the static call
  5. test an expiry rule without sleeping

basics

~20 s

java.time.Clock is a replaceable source of the current instant and a time-zone. systemUTC reads the real clock, fixed always returns one instant, and offset shifts another clock by a duration. Injecting one makes time-dependent code testable.

solid answer

~50 s

`java.time.Clock` is an abstract class that supplies the current instant together with a `ZoneId`, so code asks an object for the time rather than a static method. `Clock.systemUTC()` reads the best available system clock and converts using UTC; `Clock.fixed(instant, zone)` returns the same instant on every call, which is its main use in tests; `Clock.offset(base, duration)` wraps another clock and adds the duration, simulating the future or the past. The date-time classes accept one through `now(Clock)`, such as `Instant.now(clock)` and `LocalDate.now(clock)`. I inject it because `Instant.now()` hard-codes the system clock, whereas a constructor parameter lets a test pin "now" and check an expiry rule without sleeping. In production `Clock.systemUTC()` gives the same instants as `Instant.now()`, while date code that relied on the default zone needs a clock in that zone, such as `Clock.system(zone)`, to keep its dates.

code

java · 36 lines
java
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;

public class ClockDemo {

    static final class Trial {
        private final Clock clock;
        private final Instant endsAt;

        Trial(Clock clock, Instant endsAt) {
            this.clock = clock;
            this.endsAt = endsAt;
        }

        boolean isOver() {
            return clock.instant().isAfter(endsAt);
        }
    }

    public static void main(String[] args) {
        Instant endsAt = Instant.parse("2026-03-01T23:30:00Z");

        Clock atEnd = Clock.fixed(endsAt, ZoneOffset.UTC);
        Clock oneSecondLater = Clock.offset(atEnd, Duration.ofSeconds(1));
        System.out.println(new Trial(atEnd, endsAt).isOver());          // false
        System.out.println(new Trial(oneSecondLater, endsAt).isOver()); // true

        // The zone changes the local date, not the instant.
        System.out.println(LocalDate.now(atEnd));                                   // 2026-03-01
        System.out.println(LocalDate.now(atEnd.withZone(ZoneId.of("Asia/Tokyo")))); // 2026-03-02
    }
}

go deeper

for a junior

Recall that a Clock hands out the current instant plus a zone, and know the three factories: systemUTC reads real time, fixed never moves, and offset adds a duration to another clock.

for a middle

Explain the wiring: a constructor parameter, then Instant.now(clock) or LocalDate.now(clock) in the code. Show that the zone only affects date conversion, never the instant, and that offset shifts time rather than zone.

for a senior

Show the judgment: find the calls that still read the system clock directly, separate a due-or-not decision from its timer, and say plainly that a fixed clock moves neither sleeps, scheduled delays nor elapsed-time measurements.

for a principal

Weigh a team rule banning direct now() calls against the churn of passing a Clock through every layer: where it pays for itself, such as billing or expiry logic, where it does not, and how the rule would be enforced.

## What a Clock is `java.time.Clock` is an abstract class, added in Java 8, that answers one question: what time is it now? It hands back an **instant** (a point on the global timeline, with no zone) through `instant()`, the same reading as epoch milliseconds through `millis()`, and a **time-zone** through `getZone()`, which date-time code uses to turn that instant into a local date or time. The purpose is in its class documentation: applications "use an object to obtain the current time rather than a static method". Because the object can be swapped, `Clock` does not promise to report the real current time. It gives the application a controlled view of what the current instant and zone are. The date-time classes accept one through a `now(Clock)` factory: `Instant.now(clock)`, `LocalDate.now(clock)`, `ZonedDateTime.now(clock)` and others. Code can also call `clock.instant()` directly. ## The factory methods | Factory | What `instant()` returns | Zone | Main use | |---|---|---|---| | `Clock.systemUTC()` | Real time from the best available system clock | UTC | Production timestamps | | `Clock.systemDefaultZone()` | Real time from the same source | The JVM's default zone | Rarely: it ties the code to the default zone | | `Clock.system(zone)` | Real time from the same source | The given zone | Production code that needs one zone's local dates | | `Clock.fixed(instant, zone)` | The same instant on every call | The given zone | Tests | | `Clock.offset(base, duration)` | `base.instant()` plus the duration | The base clock's zone | Simulating the future or the past | | `Clock.tick(base, duration)` | The base instant truncated to the duration | The base clock's zone | Coarser readings, as with `tickSeconds(zone)` | Three details catch people out: - **The zone does not change the instant.** `Clock.systemUTC().instant()` and `Clock.system(ZoneId.of("Asia/Tokyo")).instant()` read the same source, so two calls made together describe the same moment. The zone matters only on conversion: a clock fixed at `2026-03-01T23:30:00Z` gives `LocalDate.now(clock)` of `2026-03-01` in UTC and `2026-03-02` in `Asia/Tokyo`. - **`offset` is a shift in time, not a time-zone offset.** It has nothing to do with `ZoneOffset`. It adds a `Duration` to every reading and keeps the base clock's zone; to change the zone, call `withZone(zone)`. - **`offset` inherits its base's behaviour.** Wrapped around a system clock it keeps ticking, ahead of or behind real time. Wrapped around a fixed clock it stays frozen at the shifted instant. A zero duration simply returns the base clock. ## Why inject one instead of calling Instant.now() `Instant.now()` takes no argument, and its documentation states the cost: using it prevents an alternate time source for testing because the clock is "effectively hard-coded". `LocalDate.now()` goes further, reading the system clock in the default zone. Passing a `Clock` into the class, which the `Clock` documentation calls best practice, gives you: - **Deterministic tests.** A test pins "now" rather than sleeping or hoping the run does not cross midnight. - **Exact boundaries.** An expiry rule can be checked at the deadline and one second after it. - **An explicit zone.** `LocalDate.now(clock)` uses the clock's zone, so a date calculation no longer depends on the machine it runs on. - **One time source.** Every class reads the same object, and an `offset` clock can run a whole test environment in the future. A dependency-injection framework is one way to supply it, and a plain constructor parameter is another. In production, `Clock.systemUTC()` reads the same source as `Instant.now()`, so instant reads do not change. Date calls are different: `LocalDate.now()` used the default zone, while `LocalDate.now(Clock.systemUTC())` uses UTC, so code that relied on the default zone needs `Clock.systemDefaultZone()`, or better `Clock.system(zone)` with the zone chosen on purpose. Use of a `Clock` remains optional: a log line's timestamp rarely justifies the extra parameter. ## Testing an expiry rule A test of "a trial is over after its end instant" reads: 1. Build `Clock.fixed(endsAt, ZoneOffset.UTC)`, which pins "now" to the deadline. 2. Construct the object under test with that clock. 3. Call the method and assert that the trial is not over yet. 4. Repeat with `Clock.offset(fixedClock, Duration.ofSeconds(1))` and assert that it is over. ## What a Clock does not control - **Code that does not ask it.** A leftover `Instant.now()` or `System.currentTimeMillis()` still reads the system clock, and `Clock` has no setter for a JVM-wide default to replace. - **Waiting.** `Thread.sleep` and `ScheduledExecutorService` delays run on real time: the scheduler takes relative delays, not absolute times, and has no `Clock` parameter. - **Elapsed-time measurement.** Subtracting two system-clock readings follows any adjustment to the wall clock, while `System.nanoTime()` is the method documented for elapsed time. To make time advance for one object during a test, subclass `Clock`: the abstract methods are `getZone`, `withZone` and `instant`, and the class contract requires every implementation to be thread-safe.

  • How do you make time advance inside a test that uses a java.time.Clock?
    For one or two steps, wrap the fixed clock with `Clock.offset(fixed, Duration.ofDays(30))` and construct the object again. When one object must see time move, subclass `Clock`, implement `getZone`, `withZone` and `instant`, and hold the current instant in an `AtomicReference`. The class contract requires every implementation to be thread-safe, which a plain mutable field does not meet.
  • Does Clock.fixed change how long Thread.sleep or a ScheduledThreadPoolExecutor delay waits?
    No. A `Clock` affects only code that asks it for the time. `Thread.sleep` still waits on system timers, and `ScheduledThreadPoolExecutor`, like every `ScheduledExecutorService`, takes relative delays with no `Clock` parameter, so a test that pins a clock and then waits on a timer waits for real. Separate the decision (is this due at this instant?) from the trigger, and test the decision with the clock.
  • When would you accept a java.time.InstantSource instead of a Clock?
    `InstantSource`, an interface added in Java 17, offers `instant()` and `millis()` without holding a zone, and `Clock` implements it. Accept it when a class only compares or stores instants, because the signature then shows that no local date is being calculated. Accept `Clock` when the code calls `LocalDate.now(clock)` or anything else that needs a zone. `withZone(zone)` turns a source into a `Clock` if that need appears later.

A clock on a film set. The crew can leave it running on real time (systemUTC), stop its hands at 3:15 for the scene (fixed), or set it two hours fast (offset). The scene works because actors read the prop clock they were given; an actor who checks a personal watch is calling Instant.now().

  • Clock.offset converts a clock to another time zone, the way a ZoneOffset does.
  • Clock.fixed starts at the given instant and then ticks forward from there.
  • Clock.system(zone).instant() returns a different moment for each zone.
  • Building a fixed Clock also changes what Instant.now() returns everywhere.
  • Injecting a Clock requires a dependency-injection framework.
  • A fixed Clock also freezes Thread.sleep and scheduled executor delays.

java.time.Clock
Java 1.8

context