2013-06-19 14 views
1

我分享我的當前時間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(); 

現在(後來在日後的源代碼),我需要的當前時間進行比較,以我保存在共享偏好,看看30天內經過的時間。

這樣做的最好方法是什麼?

回答

6

所有的第一次,在這條線,你應該更改爲:

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 
} 
+0

謝謝! P.S. 我收到一個錯誤,指出類型SharedPreferences中的方法getLong(String,long)不適用於參數(字符串)「\t - 任何建議? – NoobDev954

相關問題