【问题标题】:How to store date as SharedPreference? [closed]如何将日期存储为 SharedPreference? [关闭]
【发布时间】:2020-03-16 09:07:44
【问题描述】:
I asked same question before but it got closed and associated with another question which not solving my problem.

当用户在一天中第一次打开应用程序时,我希望应用程序每天执行一次特定的操作。为此,我想在 SharedPreference 中存储一个日期。但它只存储 int、boolean、string 等。

/*

I'm showing my logic here. If there is better way plz tell me!!!
I will give some by default value like 00/00/0000 for initialization.
The first time user starts the app then I will do that particular work and initialize sharedPreference by current date 16/03/2020. 
If user again opens app by same date I don't do that work(By checking curdate and sharedPreference date).
If user opens app on another date I check currentDate and sharedPreference date, if they are different I will do that work and edit the sharedPreference by that day.
*/

那么告诉我如何在 sharedPreference 中存储日期?

【问题讨论】:

  • 你要存储什么样的数据
  • 您需要将Date转换为String并存储到SharedPreference。如果您想获取该日期,请从SharedPreference 获取日期并将String 转换为Date
  • 您可以将对象转换为json字符串然后存储
  • 只需将数据转换为字符串并存储到 sharedPreference 中,当您再次获取它时将其转换为简单日期
  • 是的,正如 Ali 和 Amit 所说,您已将 Date 对象转换为 String 并保存。

标签: android date logic sharedpreferences


【解决方案1】:

您可以通过将日期转换为字符串来将日期保存在 SharedPreferences 中。 请通过“savedates”方法找到保存日期的示例。您将以字符串形式传递上下文和日期。 context 将是当前上下文。

    public static void savedates(Context context, String date) {
    SharedPreferences.Editor editor = context.getSharedPreferences("MyPref", MODE_PRIVATE).edit();
    editor.putString("datestr", date);
    editor.apply();
}

    public static String getDates(Context context) {
    SharedPreferences prefs = context.getSharedPreferences("MyPref", MODE_PRIVATE);
     return prefs.getString("datestr", "");
}

【讨论】:

  • 我只是举了一个例子。他们可以根据她/他的要求进行修改。
【解决方案2】:
//create sharedpreference object
 SharedPreferences.Editor myeditor = context.getSharedPreferences("MyPref", MODE_PRIVATE).edit();

// to get current date.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format(new Date());

//store date in sharedpreference
myeditor.putString("mydate",date);
myeditor.commit();

【讨论】:

  • 我结合了这两个答案。所以也谢谢你!!!
  • 请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API, 和它的DateTimeFormatter 中做得更好。是的,您可以在 Android 上使用它。对于较旧的 Android,请参阅 How to use ThreeTenABP in Android Project
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 2013-07-28
  • 2013-11-07
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多