How to save and retrieve Date in SharedPreferences

前端 未结 3 1273
Happy的楠姐
Happy的楠姐 2020-12-02 14:30

I need to save a few dates in SharedPreferences in android and retrieve it. I am building reminder app using AlarmManager and I need to save list o

3条回答
  •  被撕碎了的回忆
    2020-12-02 14:57

    To save and load accurate date, you could use the long (number) representation of a Date object.

    Example:

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

    You can use this to save or retrieve Date/Time data from SharedPreferences like this

    Save:

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

    Read it back:

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

    Edit

    If you want to store the TimeZone additionaly, you could write some helper method for that purpose, something like this (I have not tested them, feel free to correct it, if something is wrong):

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

提交回复
热议问题