问题描述
我的Android应用程序中有些东西每天需要更新一次。
I have some things in my Android application that need to update once per day.
我认为这很简单,但是我不知道我需要哪种格式格式化日期和时间(如果需要时间)以及如何检查今天是否已完成更新(今天是用户本地时间的上午00:01到23:59 pm之间)。如果今天已完成更新,则不应该进行更新。
It's pretty simple I think, but I have no idea in what format I need to format the date and time (if time is needed) and how to check if an update has been done today (where today is between 00:01am and 23:59pm in the user's local time). The update should not be done if it was already done for today.
这是我确实知道的操作:
Here's what I DO know how to do:
- 在SharedPreferences中保存最近的更新日期(但是我不知道如何获取它的
字符串) - 获取内容来自SharedPreferences(但我
不知道如何比较字符串格式的日期)
推荐答案
选择哪种格式无关紧要。这只是重新计算的问题。
It is irrelevant what format you choose. It is just matter of recalculations.
我建议使用自纪元以来的毫秒数,因为所有系统调用都使用它,因此使用它会更容易。
I'd suggest using milliseconds since epoch, as all system calls use it, so it would be easier for you to use the same.
由于1000毫秒是1秒,因此很容易弄清 1000 * 60 * 60 * 24
等于1天(24小时)。因此,如果 storedMillis
现在大于-1000 * 60 * 60 * 24
,(和 NOW
即 System.currentTimeMillis()
),那么现在进行检查还为时过早。如果 storedMillis
较小,则保存您的 NOW
时间戳并进行检查:
As 1000 millis is 1 second it's easy to figure out that 1000*60*60*24
equals to one day (24hrs). So, if storedMillis
is bigger than NOW - 1000*60*60*24
, (and NOW
is i.e. System.currentTimeMillis()
), then it is too early to do the check. If storedMillis
is smaller, then save your NOW
timestamp and do the check:
long now = System.currentTimeMillis();
long diffMillis = now - lastCheckedMillis;
if( diffMillis >= (3600000 * 24) ) {
// store now (i.e. in shared prefs)
// do the check
} else {
// too early
}
编辑
这是如何获取合适的毫秒数来比较的问题。将上述代码中的 long now = System.currentTimeMillis();
替换为以下代码块:
It's just the matter how to get the proper millis to compare against. Replace long now = System.currentTimeMillis();
from above code with following code block:
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR);
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
long now = cal.getTimeInMillis();
这可以解决问题。
这篇关于每天仅更新一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!