将当前时间(以毫秒为单位)与共享首选项中保存的时间进行比较 [英] comparing current time in milliseconds to time saved in shared preferences

查看:30
本文介绍了将当前时间(以毫秒为单位)与共享首选项中保存的时间进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用以下方法在 sharedPreferences 中分享了我的当前时间:

I've shared my current time in sharedPreferences using the following method:

Date date = new Date(System.currentTimeMillis());

Date date = new Date(System.currentTimeMillis());

SharedPreferences pref = getApplicationContext().getSharedPreferences("DataCountService", 0);
long millis = date.getTime();
SharedPreferences.Editor editor = pref.edit();
editor.putLong("smstimestamp", date.getTime());
editor.commit();

现在(稍后在源代码中)我需要将当前时间与我在共享首选项中保存的时间进行比较,以查看 30 天是否已经过去.

Now (later in the source code at a later date) I need to compare the current time to the time I saved in shared preferences to see if 30 days has elapsed.

这样做的最佳方法是什么?

What is the best method of doing this?

推荐答案

首先,在这一行你应该改为:

1st of all, on this line you should change to:

editor.putLong("smstimestamp", System.currentTimeMillis());

无需创建日期然后再次获取毫秒.

there's no need to create a date and then get the millis again.

现在比较一下:

//             milli min  hour  day 30day
long days_30 = 1000 * 60 * 60 * 24 * 30;
SharedPreferences pref = getApplicationContext().getSharedPreferences("DataCountService", 0);
long oldTime = pref.getLong("smstimestamp");
if(System.currentTimeMillis() - oldTime > days_30){
      // here, more than 30 days
}

这篇关于将当前时间(以毫秒为单位)与共享首选项中保存的时间进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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