Java Data Type How to - Create StopWatch from Duration








Question

We would like to know how to create StopWatch from Duration.

Answer

import java.time.Duration;
/*from www .  ja  v a  2  s. com*/
public class StopWatch {

  private long startTime = System.nanoTime();

  public Duration time() {
    return Duration.ofNanos(System.nanoTime() - startTime);
  }

  public Duration reset() {
    long now = System.nanoTime();
    long duration = (now - startTime) / 1000000L;
    startTime = now;
    return Duration.ofNanos(duration);
  }
}