Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Duration

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

Any idea on how to calculate the duration? Preferably in a very simple manner

Any help is very welcome

Regards, MilindaD

like image 654
MilindaD Avatar asked Apr 06 '11 07:04

MilindaD


People also ask

How do you calculate duration?

What is the Duration Formula? The formula for the duration is a measure of a bond's sensitivity to changes in the interest rate, and it is calculated by dividing the sum product of discounted future cash inflow of the bond and a corresponding number of years by a sum of the discounted future cash inflow.

What is duration time example?

Duration is how long something lasts, from beginning to end. A duration might be long, such as the duration of a lecture series, or short, as the duration of a party.

What is the time of duration?

A Duration measures an amount of time using time-based values (seconds, nanoseconds). A Period uses date-based values (years, months, days). Note: A Duration of one day is exactly 24 hours long.


2 Answers

Just use System.currentTimeMillis() to capture the time when the activity starts and stops. E.g.:

long startTime = System.currentTimeMillis();
// wait for activity here
long endTime = System.currentTimeMillis();
long seconds = (endTime - startTime) / 1000;
like image 81
WhiteFang34 Avatar answered Oct 24 '22 06:10

WhiteFang34


As of Java 8 there is more convenient way of doing this.

Instant start = Instant.now();
...
Duration.between(start, Instant.now())

Benefit of this approach is more flexible API provided by the Duration class.

https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html

like image 27
Łukasz Wachowicz Avatar answered Oct 24 '22 05:10

Łukasz Wachowicz