Skip to content

Instantly share code, notes, and snippets.

@nightuser
Last active November 28, 2023 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nightuser/d764d94ffb75d39fff7546f56fb3fc69 to your computer and use it in GitHub Desktop.
Save nightuser/d764d94ffb75d39fff7546f56fb3fc69 to your computer and use it in GitHub Desktop.
Java Adjustable Clock
package fun.nightuser;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class AdjustableClock extends Clock {
private Clock fixedClock;
public AdjustableClock(Instant fixedInstant, ZoneId zone) {
fixedClock = Clock.fixed(fixedInstant, zone);
}
public AdjustableClock(Instant fixedInstant) {
this(fixedInstant, ZoneOffset.UTC);
}
private AdjustableClock(Clock innerClock) {
fixedClock = innerClock;
}
@Override
public ZoneId getZone() {
return fixedClock.getZone();
}
@Override
public Clock withZone(ZoneId zone) {
return new AdjustableClock(fixedClock.withZone(zone));
}
@Override
public Instant instant() {
return fixedClock.instant();
}
public void advance(Duration offset) {
fixedClock = Clock.offset(fixedClock, offset);
}
}
package fun.nightuser;
import java.time.Duration;
import java.time.Instant;
public class Main {
public static void main(String[] args) {
AdjustableClock clock = new AdjustableClock(Instant.now());
Instant time1 = clock.instant();
System.out.println(time1);
clock.advance(Duration.ofHours(1));
Instant time2 = clock.instant();
System.out.println(time2);
clock.advance(Duration.ofMinutes(25));
Instant time3 = clock.instant();
System.out.println(time3);
Duration offset = Duration.between(time1, time3);
System.out.println(offset);
if (offset.compareTo(Duration.ofMinutes(70)) >= 0) {
System.out.println("At least 70 minutes have passed");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment