java - How to get time difference between two dates in Android App? -
i'm trying implement time counter (counts 0) gets saved time variable (starttime, created user tapped button) , subtracts current time (calendar.getinstance() maybe?) result difference (in hh:mm:ss) between 2 times. method run on every tick of chronometer text view updated every second, creating timer.
now, take roundabout route because it's way figure out conserve elapsed time if app killed. because starttime variable gets saved sharedpreferences it's created, , during each tick, system calculates timer on spot finding difference between starttime , current time.
now, i've tried making starttime calendar variable , initialised such:
calendar starttime = calendar.getinstance();
and then
elapsedtime = starttime - calendar.getinstance();
but evidently, doesn't work.
in similar project, written in c#, able work, albeit using datetime variable... there such way in android?
if way convoluted, there better way conserve chronometer progress?
please , thank you!
using sharedpreference
store start time right if have single start time, although want store calendar.getinstance().gettimeinmillis()
instead of object itself. can restore using
long startmillis = msharedpreferences.getlong(start_time_key, 0l); calendar starttime = calendar.getinstance(); starttime.settimeinmillis(millis);
computing difference easier milliseconds:
long = system.currenttimemillis(); long difference = - startmillis;
you can output using dateutils.formatelapsedtime():
long differenceinseconds = difference / dateutils.second_in_millis; // formatted hh:mm:ss or mm:ss string formatted = dateutils.formatelapsedtime(differenceinseconds);
Comments
Post a Comment