为SharedPreferences存储时间的正确方法是什么? 这是我的想法,但我得到一个错误:类型不匹配:无法从Time转换为long。我应该用什么格式存储它?
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
long time2 = today;
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("lastUpdated", time2);
editor.commit();
答案 0 :(得分:2)
您是否需要维护时区本身,或者只是及时表示?如果是后者,只需致电Time.toMillis
即可返回long
。如果您还需要保留时区,我只需将时区ID存储在单独的字符串中。
然后,您可以稍后通过创建新实例(使用适当的时区)并致电Time.set
来返回Time
。
(根据您的确切背景,您需要确定是否传递true
或false
ignoreDst
。文档中有一些建议。)
答案 1 :(得分:1)
您可以使用:
SharedPreferences preferences = null;
preferences = act.getSharedPreferences("PREFS_NAME",
Activity.MODE_PRIVATE);
preferences.edit().putString("TIME", getCurrentTimeDate())
.commit();
并使用此方法来获取时间。
private String getCurrentTimeDate() {
Calendar calendar = new GregorianCalendar();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return formatter.format(calendar.getTime());
}
答案 2 :(得分:0)
使用日期而不是时间:
Date today = new Date();
long time2 = today.getTime();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("lastUpdated", time2);
editor.commit();