How to store a Date object in SharedPreferences?

前端 未结 4 1140
鱼传尺愫
鱼传尺愫 2021-01-01 18:10

Is it possible to store a Date object using SharedPreferences?

Actually in my code I have a String variable, boolean

相关标签:
4条回答
  • 2021-01-01 18:20

    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

    0 讨论(0)
  • 2021-01-01 18:24
    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);
    
    0 讨论(0)
  • 2021-01-01 18:27

    you can store the date value using sharedpreferences like this way

    editor.putLong("date",currentDate.getTime());
    
    0 讨论(0)
  • 2021-01-01 18:29

    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()); 
    
    0 讨论(0)
提交回复
热议问题