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:
systemDefaultZone()
systemUTC()
…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?
A clock providing access to the current instant, date and time using a time-zone. Instances of this class are used to find the current instant, which can be interpreted using the stored time-zone to find the current date and time. As such, a clock can be used instead of System. currentTimeMillis() and TimeZone.
Java Clock class is present in java. time package. It was introduced in Java 8 and provides access to current instant, date, and time using a time zone. The use of the Clock class is not mandatory because all date-time classes also have a now() method that uses the system clock in the default time zone.
The Clock Class The Clock class is abstract, so we cannot create an instance of it. The following factory methods can be used: offset(Clock, Duration) – returns a clock that is offset by the specified Duration.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With