简体   繁体   English

如何在Android App中获取两个日期之间的时差?

[英]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. 我正在尝试实现一个时间计数器(从0开始计数),它基本上得到了保存的时间变量(startTime,它是在用户点击一个按钮时创建的)并减去当前时间(Calendar.getInstance()可能?这样结果就是两次之间的差异(HH:MM:SS)。 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. 这是因为startTime变量在创建后立即保存到SharedPreferences,并且在每个Tick中,系统只需找到startTime和当前时间之间的差异即可在现场计算我的计时器。

now, I've tried making my startTime a Calendar variable and initialised as such: 现在,我已经尝试将我的startTime作为Calendar变量并初始化为:

 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? 在一个用C#编写的类似项目中,我能够使用它,虽然使用了DateTime变量......在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. 如果您只有一个开始时间,则使用SharedPreference来存储开始时间是完全正确的,尽管您可能希望存储Calendar.getInstance().getTimeInMillis()而不是对象本身。 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() : 然后,您可以使用DateUtils.formatElapsedTime()输出它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM