在文件中存储日期的方法是什么?
我正在编写一个小型 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的方法可能是使用 SharedPreferences:
保存在首选项中:
恢复:
Easiest way is probably to use the SharedPreferences:
Save in prefs:
Restore:
根据我的经验,存储
Date
的最佳方法是存储它的 UNIX Epoch 时间,它将节省您解析它的时间/代码。
检索日期时,只需使用
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,It'll save you the time/code from parsing it.
When retrieving the Date, just use the
new Date(long date)
Constructor or theCalendar
class also hassetTimeinMillis
.Good Luck.
将其保存到应用程序首选项中。在您的 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.