Java Clock fixed()
May 16, 2019
Java Clock.fixed
returns a fixed clock that always gives the same instant. The fixed clock simply returns the specified instant. The main use case of fixed clock is in testing, where the fixed clock ensures tests are not dependent on the current clock.
Find the
Clock.fixed
declaration from Java doc.
public static Clock fixed(Instant fixedInstant, ZoneId zone)
Clock.fixed
method. Clock.fixed Example
We can create a fixed clock usingClock.fixed
as following.
Instant instant = Instant.parse("2018-01-08T15:34:42.00Z"); ZoneId zoneId = ZoneId.of("Asia/Calcutta"); Clock clock = Clock.fixed(instant, zoneId);
clock
object will always give the same instant as specified. Find the example.
FixedClockDemo.java
package com.concretepage; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; public class FixedClockDemo { public static void main(String[] args) { Instant instant = Instant.parse("2018-01-08T15:34:42.00Z"); ZoneId zoneId = ZoneId.of("Asia/Calcutta"); Clock clock = Clock.fixed(instant, zoneId); for (int i = 1; i <= 3; i++) { System.out.println("-----" + i + "-----"); System.out.println(clock.instant()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
-----1----- 2018-01-08T15:34:42Z -----2----- 2018-01-08T15:34:42Z -----3----- 2018-01-08T15:34:42Z
Clock.fixed with Offset
We can add or subtract time to fixed clock using itsClock.offset
method. Suppose we have a fixed clock.
Clock clock = Clock.fixed(instant, zoneId);
Clock clockPlus = Clock.offset(clock, Duration.ofMinutes(20));
Clock clockMinus = Clock.offset(clock, Duration.ofMinutes(-10));
FixedClockOffset.java
package com.concretepage; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; public class FixedClockOffset { public static void main(String[] args) { Instant instant = Instant.parse("2019-01-08T15:34:42.00Z"); ZoneId zoneId = ZoneId.systemDefault(); Clock clock = Clock.fixed(instant, zoneId); Clock clockPlus = Clock.offset(clock, Duration.ofMinutes(20)); Clock clockMinus = Clock.offset(clock, Duration.ofMinutes(-10)); for (int i = 1; i <= 3; i++) { System.out.println("-----" + i + "-----"); System.out.println("Base: " + clock.instant()); System.out.println("Plus: " + clockPlus.instant()); System.out.println("Minus: " + clockMinus.instant()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
-----1----- Base: 2019-01-08T15:34:42Z Plus: 2019-01-08T15:54:42Z Minus: 2019-01-08T15:24:42Z -----2----- Base: 2019-01-08T15:34:42Z Plus: 2019-01-08T15:54:42Z Minus: 2019-01-08T15:24:42Z -----3----- Base: 2019-01-08T15:34:42Z Plus: 2019-01-08T15:54:42Z Minus: 2019-01-08T15:24:42Z
References
Java Doc: Class ClockJava Clock