How to save and retrieve Date in SharedPreferences

前端 未结 3 1269
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:42

    You can do this:

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

    To save a date:

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

    To retrieve:

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

    Hope it help.

提交回复
热议问题