How to store a Date object in SharedPreferences?

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?

  • Android ContentProvider calls bursts of setNotificationUri() to CursorAdapter when many rows are inserted with a batch operation
  • Using Observable in Android
  • Circle pager indicator doesn't look round
  • Get current wallpaper absolute path?
  • How to control ActionBar split programmatically?
  • Vertical content align in Android EditText
  • 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?

  • Bitmap recycle with largeHeap enabled
  • RelativeLayout center vertical
  • Setting textSize in custom view results in huge text
  • Adding items to Endless Scroll RecyclerView with ProgressBar at bottom
  • What is an Android PendingIntent?
  • android string.xml reading html tags problem
  • 4 Solutions collect form web for “How to store a Date object in SharedPreferences?”

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

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

    you can store the date value using sharedpreferences like this way

    editor.putLong("date",currentDate.getTime());
    

    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

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.