Skip to content

Instantly share code, notes, and snippets.



Last active Feb 10, 2020
What would you like to do?
date & time formatting & de/serialization with Gson and ThreeTenABP
dependencies {
implementation ""
implementation "com.jakewharton.threetenabp:threetenabp:1.2.2"
val dateTime: OffsetDateTime //this comes from the backend in format "2016-10-26T12:00:00-06:00"
val stringDate = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(dateTime) //shows the date in locally adapted format
private fun createGson(): Gson = GsonBuilder()
.registerTypeAdapter(, OffsetDateTimeTypeAdapter())
class OffsetDateTimeTypeAdapter : JsonSerializer<OffsetDateTime>, JsonDeserializer<OffsetDateTime> {
override fun serialize(
src: OffsetDateTime,
typeOfSrc: Type,
context: JsonSerializationContext
): JsonElement = JsonPrimitive(FORMATTER.format(src))
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext
): OffsetDateTime = FORMATTER.parse(json.asString, OffsetDateTime.FROM)
companion object {
private val FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME //
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment