Skip to content

Why does the java.time.Clock has zone information?

Why does java.time.Clock has zone information? From the Clock you only can get an Instant when calling the instant() method – which is a time without zone info.

Is the only purpose to have the zone available in the clock to e.g. create a ZonedDateTime like this?
ZonedDateTime.ofInstant(clock().instant(), clock().getZone())

Wouldn’t it then make sense to have a method zonedDateTime() in the Clock class?

Answer

Alternate clock behaviors

Quoting the Clock documentation (emphasis mine):

Use of a Clock is optional. All key date-time classes also have a now() factory method that uses the system clock in the default time zone. The primary purpose of this abstraction is to allow alternate clocks to be plugged in as and when required. Applications use an object to obtain the current time rather than a static method. This can simplify testing.

For example, Clock.fixed( Instant fixedInstant, ZoneId zone ) always reports the current moment as a specific moment, a fixed (non-changing) point in time.