Android開発で、SharedPreferencesを用いて日時を保存して、
取り出す際に日付型で取得する方法のまとめ。
日付を扱うクラスはDate、Calendar、LocalDate、LocalDateTime、LocalTimeがよくあるかな
と思うのでこの辺をまとめてみます。
Dateクラス
保存
- val date = Date() // 保存対象
- val format = SimpleDateFormat("yyyyMMddHHmmssSSSS", Locale.getDefault())
- sharedPreferences.edit().putString("Date", format.format(date)).apply()
復元
- // Dataがない場合はnullを設定する
- val format = SimpleDateFormat("yyyyMMddHHmmssSSSS", Locale.getDefault())
- val date = sharedPreferences.getString("Date", null)?.let{ format.parse(it)}
Calendarクラス
いったんDateに変換して保存する感じ保存
- val calc = Calendar.getInstance() // 保存対象
- val format = SimpleDateFormat("yyyyMMddHHmmssSSSS", Locale.getDefault())
- val data = calc.time
- sharedPreferences.edit().putString("Date", format.format(data)).apply()
復元
- // Dataがない場合はnullを設定する
- val format = SimpleDateFormat("yyyyMMddHHmmssSSSS", Locale.getDefault())
- val calc = sharedPreferences.getString("Date", null)?.let{format.parse(it)}
- ?.let { GregorianCalendar().apply{ time = it }}
LocalDateクラス
※APIlevel26からなので、Android8未満をサポートするなら使用不可保存
- val date = LocalDate.now() // 保存対象
- sharedPreferences.edit().putString("Date", date.toString()).apply()
復元
※LocalDateTime、LocalTimeも同様
- // Dataがない場合はnullを設定する
- val localdate = sharedPreferences.getString("Date", null)?.let{LocalDate.parse(it)}
ソースコードのまとめ
一応、Java版も含め、ソースコードのみをGitHubに上げておく
0 件のコメント:
コメントを投稿