5

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!

iVikD
  • 296
  • 7
  • 21
  • 1
    Java does not support operator overloading, so there's no way to use the `-` operator on anything except primitive numeric types (not even `BigInteger`). – ajb Aug 18 '14 at 02:38
  • possible duplicate of [Calculate Time Difference in Android](http://stackoverflow.com/questions/5127666/calculate-time-difference-in-android) – Andrew T. Aug 18 '14 at 02:40
  • 1
    If the only thing you're going to do with these time values is subtract them to get the elapsed time, perhaps [`System.currentTimeMillis`](http://developer.android.com/reference/java/lang/System.html#currentTimeMillis()) is good enough for your purposes? – ajb Aug 18 '14 at 02:41

1 Answers1

16

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);
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443