Please tell me how to save a Date (Date ddd;) in SharedPreferences and then compare ddd with the current date? The standard form for writing the variable SharedPreferences looks like this, but how can I get a date there?

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(R.string.saved_high_score), newHighScore); editor.commit(); 
  • As an option to keep the line, and when you need to get a date, then convert the line to a date via DateFormatter - Android Android

2 answers 2

Save as long

 Date date = new Date() SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putLong("date", date.getTime()); editor.commit(); 

Then compare two long 'a

  • for some reason, Android Studio swears at the first line of SharedPreferences, writes - can not resolve method getActivity () - Hellraiser
  • one
    @ user194394 This code is for the fragment. In the activation, the call to the getActivity() method should be skipped - SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); / Even a novice developer should understand such simple things. - pavlofff
  • Thank you all - Hellraiser

You just need to know that Date is in fact a wrapper over ordinary Long . Date has a getTime() method that returns the number of milliseconds since 1980 (I don’t remember the exact date). Save the value that g etTime() returns. You can restore it by passing it to the long constructor, which you will get from SharedPreferences .

  • 2
    If not mistaken, it returns the number of milliseconds from 00:00 01.01. 1970 GMT. - Yuriy SPb
  • @ YuriySPb, Probably it is - Vladyslav Matviienko