問題描述
我需要在 android 的 SharedPreferences
中保存一些日期并檢索它.我正在使用 AlarmManager
構建提醒應用程序,我需要保存未來日期列表.它必須能夠以毫秒為單位進行檢索.首先,我想計算現在時間和未來時間之間的時間并存儲在共享偏好中.但該方法不起作用,因為我需要將它用于 AlarmManager
.
I need to save a few dates in SharedPreferences
in android and retrieve it. I am building reminder app using AlarmManager
and I need to save list of future dates. It must be able to retrieve as milliseconds. First I thought to calculate time between today now time and future time and store in shared preference. But that method is not working since I need to use it for AlarmManager
.
推薦答案
要保存和加載準確的日期,可以使用 Date
的 long
(數字)表示對象.
To save and load accurate date, you could use the long
(number) representation of a Date
object.
示例:
//getting the current time in milliseconds, and creating a Date object from it:
Date date = new Date(System.currentTimeMillis()); //or simply new Date();
//converting it back to a milliseconds representation:
long millis = date.getTime();
您可以使用它從 SharedPreferences
中保存或檢索 Date
/Time
數據,如下所示
You can use this to save or retrieve Date
/Time
data from SharedPreferences
like this
保存:
SharedPreferences prefs = ...;
prefs.edit().putLong("time", date.getTime()).apply();
回讀:
Date myDate = new Date(prefs.getLong("time", 0));
編輯
如果你想額外存儲 TimeZone
,你可以為此編寫一些輔助方法,類似這樣(我沒有測試過它們,如果有問題,請隨時更正):
If you want to store the TimeZone
additionaly, you could write some helper method for that purpose, something like this (I have not tested them, feel free to correct it, if something is wrong):
public static Date getDate(final SharedPreferences prefs, final String key, final Date defValue) {
if (!prefs.contains(key + "_value") || !prefs.contains(key + "_zone")) {
return defValue;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(prefs.getLong(key + "_value", 0));
calendar.setTimeZone(TimeZone.getTimeZone(prefs.getString(key + "_zone", TimeZone.getDefault().getID())));
return calendar.getTime();
}
public static void putDate(final SharedPreferences prefs, final String key, final Date date, final TimeZone zone) {
prefs.edit().putLong(key + "_value", date.getTime()).apply();
prefs.edit().putString(key + "_zone", zone.getID()).apply();
}
這篇關于如何在 SharedPreferences 中保存和檢索日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!