How to serialize Duration?

Kotlin has a Duration class that is usable in JVM and JS. But how to serialize it between the two? I know how to write a serializer, so I’m really asking: how to round trip a Duration with some other primitive value(s).

Does this always pass?

val dur: Duration = ...
assertEquals(dur.inSeconds.seconds, dur)

You can use the ISO 8601 standard.
Otherwise you can encode duration in decimal seconds.

If you need exact conversion, please consider to avoid to use Double.

The class has toIsoString() but it appears I have to write the inverse (the parser) myself. It shouldn’t be too hard, but once I have the components, as ints or doubles, there is no obvious API to construct a Duration from components. Yes, I can do something like

 val d: Duration = dayPart.days + hourPart.hours + ...

But depending on the class internals, I might get floating point rounding and not get the exact same Duration after a round trip.

Java provides a parser out of the box, you can use a third-party library in Javascript.

Finally, you can contribute to the official KEEP with your use case to include the parser in the Kotlin library.