Java.Time.LocalDateTime Converter For Room (Kotlin)

April 14, 2018

Create converter for java.time.LocalDateTime to epoch milli seconds.

class Converters {
    @TypeConverter
    fun fromTimestamp(value: Long?): LocalDateTime? {
        return value?.let { LocalDateTime.ofInstant(Instant.ofEpochMilli(value), ZoneOffset.UTC) }
    }

    @TypeConverter
    fun dateToTimestamp(date: LocalDateTime?): Long? {
        return date?.atZone(ZoneOffset.UTC)?.toInstant()?.toEpochMilli()
    }
}

Register Converters with RoomDatabase.

@Database(...)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
    ...
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.