Android - calculations with time elapsed in the Chronometer

user2134555 picture user2134555 · Nov 8, 2012 · Viewed 12.9k times · Source

In Chronometer, how can we extract the time elapsed and store it separately in variables.

For example, store the number of hours, minutes, seconds elapsed in separate int variables?

Is it possible? If Yes, How?

Apart from Chronometer can it be better done using some other concept? If Yes, what is it?

Answer

flawyte picture flawyte · Nov 8, 2012

You can get the time value (in milliseconds) doing that :

long timeElapsed = SystemClock.elapsedRealtime() - chrono.getBase();

Then you can simply retrieve the hours, minutes and seconds as follows :

long timeElapsed = 7564000; //For example
int hours = (int) (timeElapsed / 3600000);
int minutes = (int) (timeElapsed - hours * 3600000) / 60000;
int seconds = (int) (timeElapsed - hours * 3600000 - minutes * 60000) / 1000;
//hours = 2
//minutes = 6
//seconds = 4