CKTIS / Java
time.Clock: practical reference
time.Clock: practical reference: Clock supplies the current instant and zone, enabling fixed clocks for deterministic time-dependent code.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.time.ClockClock supplies the current instant and zone, enabling fixed clocks for deterministic time-dependent code.
Inject Clock into code that asks for the current time, using fixed, offset, or tick clocks for deterministic tests and controlled behavior.
A wall clock can move backward or jump and is not a monotonic duration timer. Calling LocalDate.now() without the injected clock silently returns to the system default clock and zone.
withZone changes the zone used to interpret instants but not the time-line instant itself. A fixed clock never advances, while a tick clock can repeat truncated values.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var clock = java.time.Clock.fixed(java.time.Instant.parse("2024-01-01T00:00:00Z"), java.time.ZoneOffset.UTC);
System.out.println(clock.instant());
}
}
Result
2024-01-01T00:00:00Z
The example exercises the documented element in a small deterministic program and compares exact standard output.