Skip to content

Instantly share code, notes, and snippets.

@mrsasha
Last active February 10, 2020 13:45
Show Gist options
  • Save mrsasha/8b5b0a3749fe38860ea2f3f5a0c24174 to your computer and use it in GitHub Desktop.
Save mrsasha/8b5b0a3749fe38860ea2f3f5a0c24174 to your computer and use it in GitHub Desktop.
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