【问题标题】: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);

      【讨论】:

        【解决方案4】:

        这是一段代码

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

        有关 SharedPreferences 的更多详细信息:https://developer.android.com/training/data-storage/shared-preferences

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-27
          • 2012-11-14
          • 1970-01-01
          • 2019-12-18
          • 1970-01-01
          • 2021-12-26
          • 1970-01-01
          • 2014-03-21
          相关资源
          最近更新 更多