如何在Android App中获取两个日期之间的时差? [英] How to get time difference between two dates in Android App?

查看:669
本文介绍了如何在Android App中获取两个日期之间的时差?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个时间计数器(从0开始计数),它基本上获取保存的时间变量(startTime,用户点击按钮后立即创建)并减去当前时间(Calendar.getInstance( )也许?)因此结果是两次之间的差异(HH:MM:SS)。这个方法将在计时器的每个刻度上运行,以便文本视图每秒更新一次,有效地创建我的计时器。

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.

现在,我采用这种迂回路线,因为这是我能够找到的唯一方法,即使应用程序被杀,也可以节省时间。这是因为startTime变量在创建后立即保存到SharedPreferences,并且在每个Tick中,系统只需找到startTime和当前时间之间的差异即可在现场计算我的计时器。

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.

现在,我已经尝试将startTime作为Calendar变量并初始化为:

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

 Calendar startTime = Calendar.getInstance();

然后

 elapsedTime = startTime - Calendar.getInstance();

但显然,这不起作用。

在一个用C#编写的类似项目中,我能够使用它,虽然使用了DateTime变量......在Android中有这样的方法吗?

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?

请谢谢!

推荐答案

使用 SharedPreference 来存储开始时间是完全正确的虽然您可能希望存储 Calendar.getInstance()。getTimeInMillis()而不是对象本身,但您只有一个开始时间。然后你可以使用

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;

然后您可以使用 DateUtils.formatElapsedTime()

long differenceInSeconds = difference / DateUtils.SECOND_IN_MILLIS;
// formatted will be HH:MM:SS or MM:SS
String formatted = DateUtils.formatElapsedTime(differenceInSeconds);

这篇关于如何在Android App中获取两个日期之间的时差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆