'Which `Clock` implementation is the default in java.time?

The java.time framework built into Java 8 and later includes the Clock class. This class provides several variations useful for testing our date-time handling code.

Instant.now( Clock.fixed​( myInstant , myZoneId ) )

Which Clock instance represents the default used implicitly in java.time calls where we do not specify a Clock?

Instant.now()

I imagine the default is either:

…but the documentation does not say which.

When doing unit-testing, sometimes we need a clock with altered behavior. But when we want to explicitly pass a Clock object that gives default behavior, what do we use?



Solution 1:[1]

Source code of Instant.now()1, which you could easily find yourself if you use an IDE2:

public static Instant now() {
    return Clock.systemUTC().instant();
}

1) Copied from OpenJDK 14
2) In Eclipse, you place cursor on now() and press F3 to see the source code.
In IntelliJ, press F4, or choose View > Jump to Source, or on a Mac ?+click.

It is guaranteed that all compliant versions of Java will do it that way, since it is part of the contract defined for the method, i.e. it is so documented in the javadoc of now():

This will query the system UTC clock to obtain the current instant.

That link leads to Clock.systemUTC().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Basil Bourque