如何在SharedPreferences中存储Date对象?

时间:2013-04-01 12:16:59

标签: android date sharedpreferences

我需要将日期对象放在共享首选项编辑器中。

将其转换为用于存储在共享首选项中的数据类型是什么?通常我们写 prefEditor.putString("Idetails1", Idetails1);表示字符串和元素。

我该怎么做?我也可以将它用于日期对象吗?

private EditText pDisplayDate;
private ImageView pPickDate;
private int pYear;
private int pMonth;
private int pDay;
/** This integer will uniquely define the dialog to be used for displaying date picker.*/
static final int DATE_DIALOG_ID = 0;

Date date;

private DatePickerDialog.OnDateSetListener pDateSetListener =
new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, 
    int monthOfYear, int dayOfMonth) {
       pYear = year;
       pMonth = monthOfYear;
       pDay = dayOfMonth;
       updateDisplay();
       displayToast();
    }
};

private void updateDisplay() {
    pDisplayDate.setText(
       new StringBuilder()
       // Month is 0 based so add 1
       .append(pMonth + 1).append("/")
       .append(pDay).append("/")
       .append(pYear).append(" ")
    );
}

private void displayToast() {
    Toast.makeText(this, 
        new StringBuilder()
        .append("Date choosen is ")
        .append(pDisplayDate.getText()),
        Toast.LENGTH_SHORT).show();
}

2 个答案:

答案 0 :(得分:6)

  

我也可以将它用于日期对象吗?

我认为您可以使用的最简单方法是将Date转换为其String表示形式。然后,您可以使用一些日期格式化器将其简单地转换回Date对象。

String dateString = date.toString();
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(<context>);
p.edit().putString("date", dateString).commit();

更新

同样@MCeley如何指出,您也可以将Date转换为long并将其长值:

long dateTime = date.getTime();
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(<context>);
p.edit().putLong("date", dateTime).commit();

答案 1 :(得分:0)

使用Calendar对象设置日期,无论何时从Preference对象更改或检索它都很容易使用。

Calendar c = Calendar.getInstance(); // use system date on first time for initialization.

long millis= pref.getLong("date",c.getTimeInMillis()); // retrieve date from Preference object in long format

c.setTimeInMillis(millis); // now set in calendar and then use it

//on date change set the year, month and day into calendar to and then stored in preference

private DatePickerDialog.OnDateSetListener pDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                pYear = year;
                pMonth = monthOfYear;
                pDay = dayOfMonth;
                c.set(pYear , pMonth , pDay ); // set into the calendar and when need to save in preference do this
                Editor edit = pref.editor();
                edit.put("date",c.getTimeInMillis());
                edit.commit();
                updateDisplay();
                displayToast();
            }
        };