Java
Clock.fixed
返回一个固定的时钟,总是给出相同的瞬间。
固定时钟只是返回指定的瞬间。
固定时钟的主要用例是在测试中,固定时钟确保测试不依赖于当前时钟。
从Java
文档中找到Clock.fixed
声明。
public static Clock fixed(Instant fixedInstant, ZoneId zone)
我们需要传递instant
和zone
,并将返回具有固定瞬间的时钟。
指定的瞬间将是由Clock.fixed
方法获得的固定时钟的固定瞬间。
Clock.fixed 方法示例
我们可以使用Clock.fixed
创建一个固定的时钟,如下所示。
Instant instant = Instant.parse("2018-01-08T15:34:42.00Z");
ZoneId zoneId = ZoneId.of("Asia/Shanghai");
Clock clock = Clock.fixed(instant, zoneId);
clock
对象将始终提供与指定相同的时刻。
FixedClockDemo.java
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 结合 Offset 方法使用
我们可以使用其 Clock.offset
方法为固定时钟添加或减去时间。
假设我们有一个固定的时钟。
Clock clock = Clock.fixed(instant, zoneId);
我们将在基本固定时钟上增加 20
分钟,并将获得固定时钟的新实例。
Clock clockPlus = Clock.offset(clock, Duration.ofMinutes(20));
现在我们将从基本固定时钟中减去 10
分钟,并获得固定时钟的新实例。
Clock clockMinus = Clock.offset(clock, Duration.ofMinutes(-10));
完整示例:
FixedClockOffset.java
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
参考文献
【1】Java Doc: Class Clock
【2】Java Clock 详解
【3】Java Clock fixed()