Android Store LocalDateTime in SharedPreferences

July 25, 2018

UTC Epoch miliseconds to LocalDateTime

val milliseconds = sharedPref.getLong(key, 0)
val localDateTime = if (milliseconds == 0L) null else LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), ZoneOffset.UTC)

LocalDateTime to UTC Epoch miliseconds

val milliseconds = localDateTime?.atZone(ZoneOffset.UTC)?.toInstant()?.toEpochMilli() ?: 0
sharedPref.edit {
    putLong(key, milliseconds)

NOTE: Android KTX is used for sharedPref.edit.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.