java 计算持续时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5562550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate Duration
提问by MilindaD
I have a small android problem, I have a requirement to have a timer to calculate the duration from the time a specific activity was open till a certain button in that activity is clicked, simply how long the activity was open. While googling around I found TimerTask but this seems to run a thread for a certain interval only though and doesent seem ideal for the job from my little Android experience
我有一个小的 android 问题,我需要一个计时器来计算从特定活动打开的时间到单击该活动中的某个按钮的持续时间,即活动打开的时间。在谷歌搜索时,我发现了 TimerTask 但这似乎只在特定时间间隔内运行一个线程,并且从我的 Android 经验来看,这似乎并不适合这项工作
Any idea on how to calculate the duration? Preferably in a very simple manner
关于如何计算持续时间的任何想法?最好以非常简单的方式
Any help is very welcome
非常欢迎任何帮助
Regards, MilindaD
问候, MilindaD
回答by WhiteFang34
Just use System.currentTimeMillis()
to capture the time when the activity starts and stops. E.g.:
仅用于System.currentTimeMillis()
捕获活动开始和停止的时间。例如:
long startTime = System.currentTimeMillis();
// wait for activity here
long endTime = System.currentTimeMillis();
long seconds = (endTime - startTime) / 1000;
回答by ?ukasz Wachowicz
As of Java 8 there is more convenient way of doing this.
从 Java 8 开始,有更方便的方法来做到这一点。
Instant start = Instant.now();
...
Duration.between(start, Instant.now())
Benefit of this approach is more flexible API provided by the Duration class.
这种方法的好处是 Duration 类提供的 API 更加灵活。
https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html
https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html
回答by FBH
group: 'org.apache.commons',name: 'commons-lang3'
组:'org.apache.commons',名称:'commons-lang3'
StopWatch stopWatch = new StopWatch();
stopWatch.start();
...
stopWatch.stop();
stopWatch.getTime(TimeUnit.SECONDS);
回答by Vivek
If you want to find out how long activity is open.
如果您想了解活动的开放时间。
You can write respective code in
您可以在
onCreate() method and onDestory() method. or
onCreate() 方法和 onDestory() 方法。或者
- onResume() method onPause() method.
- onResume() 方法 onPause() 方法。
depending on your need.
取决于您的需要。
and make use of following code
并使用以下代码
long t1 = new Date().getTime();
long t2 = new Date().getTime();
long t3 = t2 - t1;