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

帅比萌擦擦* 提交于 2020-01-02 04:35:06

问题


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!


回答1:


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);


来源:https://stackoverflow.com/questions/25355611/how-to-get-time-difference-between-two-dates-in-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!