Last active
November 28, 2023 11:36
-
-
Save nightuser/d764d94ffb75d39fff7546f56fb3fc69 to your computer and use it in GitHub Desktop.
Java Adjustable Clock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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