The Clock
class is part of the java.time
package and provides an abstraction to access the current instant, date, and time using a time-zone.This abstract an class.
It allows applications to:
- Get the current time in a consistent and testable way.
- Work with different time zones or offsets.
- Be used to inject clocks for unit testing.
Common used Methods

Simple Program
import java.time.Clock; import java.time.Instant; import java.time.ZoneId; public class ClockExample { public static void main(String[] args) { Clock utcClock = Clock.systemUTC(); Clock defaultClock = Clock.systemDefaultZone(); System.out.println("UTC Time: " + Instant.now(utcClock)); System.out.println("System Default Zone: " + defaultClock.getZone()); System.out.println("Local Time: " + Instant.now(defaultClock)); } }
Problem Statement
LotusJavaPrince and Mahesh are developing a logging system that uses:
- A system clock for production logs.
- A fixed clock for testing.
- An offset clock for simulating server lag.
The goal is to demonstrate consistent, testable, and simulated time using the Clock
class.
import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; public class LoggingSystem { public static void main(String[] args) { System.out.println("Logging System - Created by LotusJavaPrince and Mahesh"); // System clock (real-time) Clock systemClock = Clock.systemDefaultZone(); // Fixed clock (mocked time) Clock fixedClock = Clock.fixed(Instant.parse("2025-01-01T00:00:00Z"), ZoneId.of("UTC")); // Offset clock (simulated 5-minute delay) Clock offsetClock = Clock.offset(systemClock, Duration.ofMinutes(-5)); // Displaying all clocks System.out.println("System Time: " + Instant.now(systemClock)); System.out.println("Fixed Time: " + Instant.now(fixedClock)); System.out.println("Offset Time (simulated delay): " + Instant.now(offsetClock)); } } /* Logging System - Created by LotusJavaPrince and Mahesh System Time: 2025-05-22T10:30:00.000Z Fixed Time: 2025-01-01T00:00:00Z Offset Time (simulated delay): 2025-05-22T10:25:00.000Z &/
The Clock
class is an essential utility in Java’s date-time API that decouples time retrieval from system time.
- Useful for testing, simulation, and time zone handling.
- Provides precise control over how time is handled in applications, like LotusJavaPrince and Mahesh’s logging system.
- When writing enterprise or production software, using
Clock
makes time-related logic more testable and configurable.