Last active
February 10, 2020 13:45
-
-
Save mrsasha/8b5b0a3749fe38860ea2f3f5a0c24174 to your computer and use it in GitHub Desktop.
date & time formatting & de/serialization with Gson and ThreeTenABP
This file contains hidden or 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
dependencies { | |
implementation "com.google.code.gson:gson:2.8.6" | |
implementation "com.jakewharton.threetenabp:threetenabp:1.2.2" | |
} |
This file contains hidden or 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
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 |
This file contains hidden or 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
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