3

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.

Andy
  • 1,454
  • 17
  • 33

4 Answers4

10

Use:

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. See also the Javadocs.

Thomas Mueller
  • 48,905
  • 14
  • 116
  • 132
  • *It doesn't take the system time into account*, often it does since TSC is virtually unreliable. Look at David Holmes [senior JVM engineer and also behind RT java] blog: https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks Cliff Click's (the original hotspot architect also keeps using currentTimeMillis - much cheaper than nanoTime). When nanoTime was introduced it had TSC register in mind but it's not consistent amongst the sockets or during power-saving modes. RFE: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6440250 – bestsss Aug 12 '12 at 13:44
4
System.nanoTime();

From Javadoc:

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
1

Use time web services . for example this or this or this

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 1
    The only problem is that you'll have to deal with the network latency, but is a fine solution for dealing with this kind of problem – Kico Lobo Aug 23 '11 at 13:50
0

You can install demon like NTP, system time jumping in any directions has a lot of issues and can lead to quite a lot of other problems.

System.nanoTime() not necessarily depend on the system clock - but it can - just make sure the system time is correctly progressing. Modifying system time is a privileged operation, so it someone does that they shall know better.

Here is a bug 13 years of age regarding the same case: http://bugs.sun.com/view_bug.do?bug_id=4290274

HTH

bestsss
  • 11,796
  • 3
  • 53
  • 63