-4

How do I save a timestamp in shared preferences for the moment when a button is clicked?

button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               //some logic...
            }
        });
Raj
  • 2,997
  • 2
  • 12
  • 30
taeC
  • 79
  • 1
  • 2
  • 9

4 Answers4

2

Here is a piece of code

Long timestamp = System.getCurrentTimeInMillis()
SharedPreferences prefs = getApplicationContext().getSharedPreferences("preferences", Context.MODE_PRIVATE);
prefs.edit().putLong("time", timestamp).commit();

More details on SharedPreferences : https://developer.android.com/training/data-storage/shared-preferences

Bruno
  • 3,872
  • 4
  • 20
  • 37
1
  in this way you can save current time in SharedPreferences 

  SharedPreferences preferences;
  button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

   preferences = getSharedPreferences("pref_namae",MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putLong("TimeStamp",System.currentTimeMillis());
    editor.apply();
        }
    });

to get value from prefercance use this code.

long timeStamp = preferences.getLong("TimeStamp",0);

umesh shakya
  • 237
  • 2
  • 12
1

Just like this:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences.edit()
            .putLong("YourKey", timestamp)
            .apply();
Peyman
  • 941
  • 8
  • 28
1

You can use SimpleDateFormat to save time in your required timestamp.

SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
    Date date=new Date(System.currentTimeMillis());
    String formatDate=simpleDateFormat.format(date);

You can refer here for other date formats. And use SharedPreference to save it.

Nainal
  • 1,728
  • 14
  • 27