如何独立于系统时间获得时间增量? [英] How to get time delta independently from system time?

查看:35
本文介绍了如何独立于系统时间获得时间增量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 编写一个简单的计时器.它有开始"和停止"按钮,以及一个文本视图,显示自计时器启动以来已经过去了多长时间.

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.

它是通过使用 System.currentTimeMillis() 设置初始时间并在循环中每秒更新当前值来实现的.

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

问题是,如果我在计时器运行时更​​改系统时间,则整个测量失败.例如,如果我将时间设置回一个月,则计时器显示负值,因为 currentTimeMillis() 现在返回的值小于初始值.

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.

推荐答案

使用:

System.nanoTime()

这应该可以.它不考虑系统时间,只能用于测量经过的时间.这就是你想要的.您需要除以 100 万才能获得经过的毫秒数.另请参阅 Javadoc.

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.

这篇关于如何独立于系统时间获得时间增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆