如何保存和共享preferences检索日期 [英] How to save and retrieve Date in SharedPreferences

查看:183
本文介绍了如何保存和共享preferences检索日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要保存在几次约会共享preferences 在Android和检索。我建立的提醒应用程序中使用 AlarmManager 和我需要保存将来的日期列表。它必须能够检索为毫秒。首先,我想计算的今天,现在的时间和未来的时间,并存储在共享preference时间。但是,这种方法是行不通的,因为我需要使用它的 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.

推荐答案

要保存和加载准确的日期,你可以使用(数字)重presentation的日期对象。

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();

您可以用它来保存或从共享$检索日期 / 时间数据p $ pferences 像这样

You can use this to save or retrieve Date/Time data from SharedPreferences like this

保存:

SharedPreferences prefs = ...;
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("time", date.getTime());
editor.commit();

读回:

Date myDate = new Date(prefs.getLong("time", 0));

修改

如果你想存储的时区 additionaly,你可以写一些辅助方法的目​​的,这样的事情(我没有测试过,随时纠正它,如果事情是错的):

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) {
    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong(key + "_value", date.getTime());
    editor.putString(key + "_zone", zone.getID());
    editor.commit();
}

这篇关于如何保存和共享preferences检索日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆