java.time.Clock.fixed()
The method java.time.Clock.fixed() returns a clock that always returns the same time. This type of clock is mainly useful in testing.
Method signature
The signature of the java.time.Clock.fixed() method is as follows:
public static Clock fixed(Instant fixedInstant, ZoneId zone)
The method is available since Java 8.
Parameters
- Instant fixedInstant: the instant to use, not null
- ZoneId zone: the time-zone that will be used to convert the instant to date-time, not null
Return value
Returns a clock that always returns the same time.
Exceptions
The method throws no exceptions.
Example usage
In the following code we use java.time.Clock.fixed():
package com.farenda.java.time; import java.time.Clock; import java.time.ZoneId; import java.util.concurrent.TimeUnit; import static java.time.Instant.ofEpochMilli; public class ClockExample { public static void main(String[] args) { Clock clock = Clock.fixed( ofEpochMilli(0), ZoneId.systemDefault()); System.out.println("Current millis: " + clock.millis()); try { // wait for a while: TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Current millis: " + clock.millis()); } }
The above code produces the following output:
Current millis: 0 Current millis: 0