Skip to content

Instantly share code, notes, and snippets.

@mrsasha

mrsasha/GsonSetup.kt

Last active Feb 10, 2020
Embed
What would you like to do?
date & time formatting & de/serialization with Gson and ThreeTenABP
dependencies {
implementation "com.google.code.gson:gson:2.8.6"
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(OffsetDateTime::class.java, OffsetDateTimeTypeAdapter())
.create()
class OffsetDateTimeTypeAdapter : JsonSerializer<OffsetDateTime>, JsonDeserializer<OffsetDateTime> {
override fun serialize(
src: OffsetDateTime,
typeOfSrc: Type,
context: JsonSerializationContext
): JsonElement = JsonPrimitive(FORMATTER.format(src))
@Throws(JsonParseException::class)
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 //https://en.wikipedia.org/wiki/ISO_8601
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment