The following code gives an example of how you design such a clock, which has an internal state of a double spped
and long startTime
. It exposes a publish method getTime()
, which will return the adjusted time in millisecond since Midnight, Jan 1st, 1970. Note that the adjustment happens after the startTime
.
The formula to calculate the adjusted time is simple. First take the real timedelta by subtracting currentTimeMillis()
by startTime
, then multiply this value by speed
to get the adjusted timedelta, then add it to startTime
to get your result.
public class VariableSpeedClock {
private double speed;
private long startTime;
public VariableSpeedClock(double speed) {
this(speed, System.currentTimeMillis());
}
public VariableSpeedClock(double speed, long startTime) {
this.speed = speed;
this.startTime = startTime;
}
public long getTime () {
return (long) ((System.currentTimeMillis() - this.startTime) * this.speed + this.startTime);
}
public static void main(String [] args) throws InterruptedException {
long st = System.currentTimeMillis();
VariableSpeedClock vsc = new VariableSpeedClock(2.3);
Thread.sleep(1000);
System.out.println(vsc.getTime() - st);
System.out.println(System.currentTimeMillis() - st);
}
}