比较当前时间(以毫秒为单位)与共享首选项中保存的时间

Noo*_*954 1 java time android sharedpreferences

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

日期日期=新日期(System.currentTimeMillis());

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

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

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

Bud*_*ius 6

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

editor.putLong("smstimestamp", System.currentTimeMillis());
Run Code Online (Sandbox Code Playgroud)

没有必要创建一个日期,然后再次获得毫克.

现在来比较一下:

//             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
}
Run Code Online (Sandbox Code Playgroud)