javatime

How to get time delta independently from system time?


I'm writing a simple timer in Java. It has Start and Stop buttons, along with a text view showing how much time has passed since the timer was started.

It's implemented by setting initial time with System.currentTimeMillis() and updating current value each second in a loop.

The problem is that if I change system time while the timer is running, the whole measurement fails. E.g., if I set time back one month, the timer shows negative value as currentTimeMillis() now returns less value than initial.

So, how do I calculate time delta which would be independent from the system time? It would be also great to make this solution cross-platform.


Solution

  • Call System.nanoTime().

    long start = System.nanoTime() ;
    

    This should do it. It doesn't take the system time into account, and can only be used to measure elapsed time. Which is what you want. You need to divide by 1 million to get the elapsed milliseconds.

    In Java 8+, use Duration to represent elapsed nanoseconds. That class offers conversion to milliseconds etc.

    Duration duration = Duration.ofNanos( System.nanoTime() - start ) ;