【问题标题】:Save timestamp in shared preferences when a button is clicked单击按钮时在共享首选项中保存时间戳
【发布时间】:2019-01-20 05:23:55
【问题描述】:
当点击button 时,如何将timestamp 保存在共享preferences 中?
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//some logic...
}
});
【问题讨论】:
标签:
android
timestamp
sharedpreferences
onclicklistener
【解决方案1】:
您可以使用 SimpleDateFormat 在所需的时间戳中节省时间。
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);
您可以参考here 了解其他日期格式。并使用 SharedPreference 来保存它。
【解决方案2】:
就像这样:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences.edit()
.putLong("YourKey", timestamp)
.apply();
【解决方案3】:
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);