如何在SharedPreferences中保存和检索日期

Isu*_*nka 52 java android calendar date sharedpreferences

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

Bal*_*des 152

要保存和加载准确的日期,可以使用对象的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();
Run Code Online (Sandbox Code Playgroud)

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

保存:

SharedPreferences prefs = ...;
prefs.edit().putLong("time", date.getTime()).apply();
Run Code Online (Sandbox Code Playgroud)

读回来:

Date myDate = new Date(prefs.getLong("time", 0));
Run Code Online (Sandbox Code Playgroud)

编辑

如果你想存储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();
}
Run Code Online (Sandbox Code Playgroud)

  • 这有效.你应该把它标记为正确. (7认同)