在文件中存储日期的方法是什么?

发布于 2024-12-17 17:37:42 字数 131 浏览 0 评论 0原文

我正在编写一个小型 Android 应用程序,让用户选择一个日期,并显示距离该日期还剩多少天。现在我想存储该日期,以便下次应用程序启动时,它将保留该信息。我在想最好将日期保存在文件中,我的问题是 - 最好如何执行此操作,以便之后可以轻松解析该日期?

I'm writing a small android app that lets the user pick a date and it shows him how many days are left to this date. Now I would like to store that date so that next time the app starts, it will keep the information. I was thinking it's probably best to save the date in a file, and my question is - how is it best to do this so it'll be easy to parse that date afterwards?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

皇甫轩 2024-12-24 17:37:42

最简单的方法可能是使用 SharedPreferences:

保存在首选项中:

  SharedPreferences settings = getSharedPreferences("my_prefs", 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putString("date", myDate);
  editor.commit();

恢复:

   SharedPreferences settings = getSharedPreferences("my_prefs", 0);
   String date = settings.getString("date", null);

Easiest way is probably to use the SharedPreferences:

Save in prefs:

  SharedPreferences settings = getSharedPreferences("my_prefs", 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putString("date", myDate);
  editor.commit();

Restore:

   SharedPreferences settings = getSharedPreferences("my_prefs", 0);
   String date = settings.getString("date", null);
茶花眉 2024-12-24 17:37:42

根据我的经验,存储 Date 的最佳方法是存储它的 UNIX Epoch 时间,

SharedPreferences settings = getSharedPreferences("my_prefs", 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putString("date", myDate.getTime() ); //getTime is a long (So store it as a string/long, doesn't really matter)
  editor.commit();

它将节省您解析它的时间/代码。

检索日期时,只需使用 new Date(long date) 构造函数,或者 Calendar 类也有 setTimeinMillis

祝你好运。

I speak from experience, The Best way to store a Date is to store it's UNIX Epoch time,

SharedPreferences settings = getSharedPreferences("my_prefs", 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putString("date", myDate.getTime() ); //getTime is a long (So store it as a string/long, doesn't really matter)
  editor.commit();

It'll save you the time/code from parsing it.

When retrieving the Date, just use the new Date(long date) Constructor or the Calendar class also has setTimeinMillis.

Good Luck.

挽清梦 2024-12-24 17:37:42

将其保存到应用程序首选项中。在您的 Activity 中,您可能有类似的内容:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.edit().putString("日期", myDate.toString()).commit();

然后,您可以从保存的字符串中恢复日期。

Save it to application preferences. In your Activity you might have somethign like:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.edit().putString("date", myDate.toString()).commit();

Then you restore your date from that saved string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文