Created
February 14, 2024 19:56
-
-
Save valokafor/86ab6595e777384f68400a54726d0507 to your computer and use it in GitHub Desktop.
Room Converter for Local Date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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