How to store a Date object in SharedPreferences?

2020-02-27 10:57发布

Is it possible to store a Date object using SharedPreferences?

Actually in my code I have a String variable, boolean and Date. Here is my function for storing all the objects except Date. So how that can be done please suggest me?

private void SavePreferences() {

    String key="1";
    String value="hello";

    int x=5;

    Date currentDate=new Date();

    SharedPreferences sharedPreferences = getPreferences(MODE_APPEND);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);

    editor.putInt("2",5);

    editor.commit();
}

So my question is how to store the Date using SharedPreferences?

4条回答
欢心
2楼-- · 2020-02-27 11:21
editor.putLong("THE_DATE", currentDate.getTime());

And you can read a Date from preferences like this:

long millis = sharedPreferences.getLong("THE_DATE", 0L);
Date theDate = new Date(millis);
查看更多
我命由我不由天
3楼-- · 2020-02-27 11:21

you can store the date value using sharedpreferences like this way

editor.putLong("date",currentDate.getTime());
查看更多
Luminary・发光体
4楼-- · 2020-02-27 11:27

Put Date as formatted String, e.g.

//for putting
Date myDate;
final String FORMAT="yyyy-MM-dd";
String prefData=SimpleDateFormat(FORMAT).format(myDate);
editor.putString("Date", prefDate);

//for reading
prefDate=settings.getString("Date", "");
Date date=new SimpleDateFormat(FORMAT).parse(prefDate);

Or you can put millis as Long

查看更多
Summer. ? 凉城
5楼-- · 2020-02-27 11:38

Set Date Time

SharedPreferences sharedPreferences = getPreferences(MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
Date dt = getSomeDate();
editor.putLong(dateTimeKey, dt.getTime());

Get Date Time

long myDate = sharedPreferences.getLong(dateTimeKey, new Date().getTime()); 
查看更多
登录 后发表回答