/** Increment by 1 second each time you look at the clock. Starts with the default system clock's instant and time-zone. Example output: 2018-05-26T14:00:12.778Z 2018-05-26T14:00:13.778Z 2018-05-26T14:00:14.778Z 2018-05-26T14:00:15.778Z 2018-05-26T14:00:16.778Z @since Java 8. */ publicfinalclassClockTickerextendsClock {
/** Simple demo of the behaviour of this class. */ publicstaticvoidmain(String... args) { ClockTickerticker=newClockTicker(); log(ticker.instant()); log(ticker.instant()); log(ticker.instant()); log(ticker.instant()); log(ticker.instant()); } privatestaticvoidlog(Object msg){ System.out.println(Objects.toString(msg)); }
/** Set the starting date-time and time-zone, but then let the time vary normally. Example output: 2018-12-25T05:00:00Z Sleep for 5 seconds... 2018-12-25T05:00:05.005Z Done. @since Java 8. */ publicfinalclassClockTimeTravelextendsClock {
/** Simple demo of the behaviour of this class. */ publicstaticvoidmain(String[] args)throws InterruptedException { ClockTimeTraveltimeTravel=newClockTimeTravel( LocalDateTime.parse("2018-12-25T00:00:00"), ZoneOffset.of("-05:00") ); log(timeTravel.instant()); log("Sleep for 5 seconds..."); Thread.currentThread().sleep(5000); log(timeTravel.instant()); log("Done."); }
/** Figure out how much time has elapsed between the moment this object was created, and the moment when this method is being called. Then, apply that diff to t0. */ private Instant nextInstant() { Instantnow= Instant.now(); longdiff= now.toEpochMilli() - whenObjectCreatedInstant.toEpochMilli(); return t0Instant.plusMillis(diff); } }
例子 小于 Java8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
The TimeSource interfaceallows you to define various implementations of a fake system clock:
publicinterfaceTimeSource {
/** Return the system time. */ longcurrentTimeMillis();
} This implementation mimics a system clock running one day in advance: publicfinalclassTimeSrcimplementsTimeSource {
/** One day in advance of the actual time.*/ @OverridepubliclongcurrentTimeMillis() { return System.currentTimeMillis() + ONE_DAY; }
import os defset_time(request): print(datetime.today()) os.environ["FAKETIME"] = "2020-01-01"# Note: time of type string must be in the format "YYYY-MM-DD hh:mm:ss" or "+15d" print(datetime.today())