69

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

4

3 回答 3

167

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

例子:

//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();

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

节省:

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

读回来:

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

编辑

如果你想存储TimeZone额外的,你可以为此目的编写一些辅助方法,像这样(我没有测试过它们,如果有问题,请随时纠正它):

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();
}
于 2012-09-09T21:58:05.217 回答
3
于 2018-10-05T20:40:11.217 回答
3

你可以这样做:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);

要保存日期:

preferences .edit().putString("mydate", sdf.format(date)).apply();

要检索:

try{
    Date date = sdf.parse(preferences.getString("myDate", "defaultValue"));
    } catch (ParseException e) {
                e.printStackTrace();
                               }

希望它有所帮助。

于 2018-10-05T13:38:54.557 回答