2

次の方法を使用して、現在の時間を sharedPreferences で共有しました。

日付 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 日が経過したかどうかを確認する必要があります。

これを行う最良の方法は何ですか?

4

1 に答える 1

8

まず、この行を次のように変更する必要があります。

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

日付を作成してミリ秒を再度取得する必要はありません。

今それを比較します:

//             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
}
于 2013-06-19T21:45:33.887 に答える