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
?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With