Как сохранить объект Date в SharedPreferences? - PullRequest
16 голосов
/ 07 июля 2011

Можно ли сохранить объект Date, используя SharedPreferences?

На самом деле в моем коде у меня есть переменная String, boolean и Date. Вот моя функция для хранения всех объектов, кроме Date. Итак, как это можно сделать, пожалуйста, предложите мне?

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

Итак, мой вопрос, как хранить Date, используя SharedPreferences?

Ответы [ 4 ]

27 голосов
/ 07 июля 2011
editor.putLong("THE_DATE", currentDate.getTime());

И вы можете прочитать Date из предпочтений, таких как:

long millis = sharedPreferences.getLong("THE_DATE", 0L);
Date theDate = new Date(millis);
3 голосов
/ 07 июля 2011

Установить дату и время

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

Дата получения Время

long myDate = sharedPreferences.getLong(dateTimeKey, new Date().getTime()); 
1 голос
/ 07 июля 2011

Положите Date в формате String, например,

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

Или вы можете указать миллис как Long

1 голос
/ 07 июля 2011

вы можете сохранить значение даты с помощью общих настроек, например, таким образом

editor.putLong("date",currentDate.getTime());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...