Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get time difference between two dates in Android App?

I'm trying to implement a time counter (counts up from 0) which basically gets the saved time variable (startTime, which was created as soon as the user tapped a button) and subtracts the current time (Calendar.getInstance() maybe?) so that the result is the difference (in HH:MM:SS) between the two times. This method will be run on every tick of a chronometer so that the text view will be updated every second, effectively creating my timer.

Now, I take this roundabout route because it's the only way I could figure out to conserve the elapsed time even if the app is killed. This is because the startTime variable gets saved to the SharedPreferences as soon as it's created, and during each Tick, the system calculates my timer on the spot by just finding the difference between the startTime and current time.

now, I've tried making my startTime a Calendar variable and initialised as such:

 Calendar startTime = Calendar.getInstance();

and then

 elapsedTime = startTime - Calendar.getInstance();

But evidently, this doesn't work.

In a similar project, written in C#, I was able to get this to work, albeit using a DateTime variable... Is there any such way in Android?

If this is just way too convoluted, is there a better way to conserve my chronometer progress?

Please and thank you!

like image 251
iVikD Avatar asked Aug 18 '14 02:08

iVikD


People also ask

How can I find the difference between two dates in Android?

By Calendar Object:getTime(); Date date2 = calendar2. getTime(); Then compare both date using compareTo, before(date) or after(date).

How do you find the difference between two dates in hours and minutes?

d("App","difference in hour is"+diff/1000/60/60); Mins = diff/1000/60; Seconds = diff/1000; Using this code I'm getting hours as a correct value.


1 Answers

Using a SharedPreference to store the start time is exactly right if you have a single start time, although you probably want to store Calendar.getInstance().getTimeInMillis() instead of the object itself. You can then restore it by using

long startMillis = mSharedPreferences.getLong(START_TIME_KEY, 0L);
Calendar startTime = Calendar.getInstance();
startTime.setTimeInMillis(millis);

Computing the difference is often easier just as milliseconds:

long now = System.currentTimeMillis();
long difference = now - startMillis;

You can then output it by using DateUtils.formatElapsedTime():

long differenceInSeconds = difference / DateUtils.SECOND_IN_MILLIS;
// formatted will be HH:MM:SS or MM:SS
String formatted = DateUtils.formatElapsedTime(differenceInSeconds);
like image 171
ianhanniballake Avatar answered Nov 01 '22 10:11

ianhanniballake