https://kotlinlang.org logo
Title
k

Kristian Nedrevold

05/20/2022, 10:46 PM
Hey, does anyone know how I can parse 2022-05-20T19:36:27Z with kotlinx-datetime?
j

jw

05/21/2022, 1:06 AM
Do it manually? ISO 8601 is pretty straightforward. Substring+toInt will get you very far. Even regex will work.
👍 1
Pull out each number, validate the divider characters, parse each number, call the factory function for the type you want with the values
r

Richard Gomez

05/21/2022, 3:04 AM
j

jw

05/21/2022, 3:09 AM
even better. i guess when it's always UTC you don't need a timezone database!
r

Richard Gomez

05/21/2022, 3:23 AM
All hail UTC.
🤘 2
On a serious note, I am merely pointing @Kristian Nedrevold in the direction of the README.
"".toInstant()
is one option, but there are many more waiting to be discovered.
3
k

Kristian Nedrevold

05/21/2022, 3:00 PM
I am trying to use it with kotlinx serialization to serialize a Json response body. What I ended up doing was just parsing it to string when receiving the object and then parsing it to LocalDateTime using "".toInstant() later. I Don't know if this is the best/most corrrect way to do it though. Maybe I should write a custom serializer that parses it correctly when receiving the body? Thanks for the tip @Richard Gomez.
j

jw

05/21/2022, 3:18 PM
A custom serializer is the way to go
👍 1
k

Kristian Nedrevold

05/21/2022, 3:22 PM
Yeah, I expected as much. I just write a custom serializer and annotate the field with @Serializable(with = MyCustomSerializer) then?
p

phldavies

05/21/2022, 3:58 PM
kotlinx-datetime includes serializers (https://github.com/Kotlin/kotlinx-datetime/blob/master/core/common/src/serializers/InstantSerializers.kt) so you likely only need to annotate the property with
@Serializable(with = InstantIso8601Serializer::class)
👍 1
1
k

Kristian Nedrevold

05/21/2022, 4:03 PM
@phldavies That works! Thanks a lot :)
👍 1