Skip to content

Instantly share code, notes, and snippets.

@valokafor
Created February 14, 2024 19:56
Show Gist options
  • Save valokafor/86ab6595e777384f68400a54726d0507 to your computer and use it in GitHub Desktop.
Save valokafor/86ab6595e777384f68400a54726d0507 to your computer and use it in GitHub Desktop.
Room Converter for Local Date
class LocalDateConverter {
@TypeConverter
fun fromTimestamp(value: Long): LocalDate? {
return if (value < 0) null
else Instant.ofEpochMilli(value)
.atZone(ZoneId.systemDefault())
.toLocalDate()
}
@TypeConverter
fun dateToTimestamp(date: LocalDate?): Long {
return date?.run {
atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli()
} ?: -1L
}
}
class LocalTimeConverter {
@TypeConverter
fun fromTimestamp(value: Long): LocalTime? {
return if (value < 0) null
else {
val minutes = TimeUnit.MILLISECONDS.toMinutes(value)
val hour = minutes / 60
val mins = minutes % 60
return LocalTime.of(hour.toInt(), mins.toInt())
}
}
@TypeConverter
fun dateToTimestamp(time: LocalTime?): Long {
return time?.run { getLong(ChronoField.MILLI_OF_DAY) } ?: -1L
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment