android 时间差 秒,如何在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!

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值