简体   繁体   中英

Proper way of storing Time in Android's SharedPreferences?

What is the proper way of storing time to SharedPreferences? This is what was on my mind, but I get an error: Type mismatch: cannot convert from Time to long. What format should I use to store it?

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
long time2 = today;
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("lastUpdated", time2);
editor.commit();

Do you need to maintain the time zone itself, or just the instant in time being represented? If it's the latter, just call Time.toMillis which will return a long . If you need to preserve the time zone as well, I'd just store the time zone ID in a separate string.

You can then get back to a Time later by creating a new instance (with the appropriate time zone) and calling Time.set .

(You'll need to figure out whether to pass in true or false for ignoreDst based on your precise context. There's some advice in the documentation.)

You can use:

SharedPreferences preferences = null;
preferences = act.getSharedPreferences("PREFS_NAME",
                Activity.MODE_PRIVATE);
preferences.edit().putString("TIME", getCurrentTimeDate())
                    .commit();

and use this method to get time.

private String getCurrentTimeDate() {

        Calendar calendar = new GregorianCalendar();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        return formatter.format(calendar.getTime());
    }

Use Date instead of Time:

Date today = new Date();
long time2 = today.getTime();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("lastUpdated", time2);
editor.commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM