2012-09-09 39 views
39

我需要在Android中保存SharedPreferences中的几个日期并检索它。我正在使用AlarmManager构建提醒应用程序,我需要保存未来日期的列表。它必须能够以毫秒为单位进行检索。首先,我想从今天到现在的时间和未来的时间计算时间,并以共享的方式存储。但是这种方法不起作用,因为我需要将它用于AlarmManager如何在SharedPreferences中保存和检索日期

回答

131

要保存并加载准确的日期,您可以使用Date对象的long(数字)表示形式。

例子:

//getting the current time in milliseconds, and creating a Date object from it: 
Date date = new Date(System.currentTimeMillis()); //or simply new Date(); 

//converting it back to a milliseconds representation: 
long millis = date.getTime(); 

您可以用它来从SharedPreferences保存或检索Date/Time数据这样

节省:

SharedPreferences prefs = ...; 
prefs.edit().putLong("time", date.getTime()).apply(); 

阅读回:

Date myDate = new Date(prefs.getLong("time", 0)); 

编辑

如果你想存储TimeZone additionaly,你可以写为此一些辅助方法,这样的事情(我没有测试过,随意纠正它,如果出现错误):

public static Date getDate(final SharedPreferences prefs, final String key, final Date defValue) { 
    if (!prefs.contains(key + "_value") || !prefs.contains(key + "_zone")) { 
     return defValue; 
    } 
    Calendar calendar = Calendar.getInstance(); 
    calendar.setTimeInMillis(prefs.getLong(key + "_value", 0)); 
    calendar.setTimeZone(TimeZone.getTimeZone(prefs.getString(key + "_zone", TimeZone.getDefault().getID()))); 
    return calendar.getTime(); 
} 

public static void putDate(final SharedPreferences prefs, final String key, final Date date, final TimeZone zone) { 
    prefs.edit().putLong(key + "_value", date.getTime()).apply(); 
    prefs.edit().putString(key + "_zone", zone.getID()).apply(); 
} 
+7

This Works。你应该把它标记为正确的。 – rplankenhorn

+0

看起来这种方式不适用于时区特定的日期。用例:存储旅行用户的日期 – Sergii

相关问题