kotlinx-datetime
kotlinx-datetime copied to clipboard
Add Unixseconds serializer
Many APIs return a unix timestamp, the seconds from the epoch as Long
.
Although the serializer is easy to create, it could be provided.
public object InstantUnixSecondsSerializer : KSerializer<Instant> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Instant", PrimitiveKind.LONG)
override fun deserialize(decoder: Decoder): Instant = Instant.fromEpochSeconds(decoder.decodeLong())
override fun serialize(encoder: Encoder, value: Instant) {
encoder.encodeLong(value.epochSeconds)
}
}
This serializer has the unpleasant property of losing some information: it doesn't preserve the nanoseconds. Making it preserve the nanoseconds would lead to recreating the InstantComponentSerializer
—maybe use that? If the nanosecond component is zero, it's omitted, like in {"epochSeconds":1642418590}
.
Sorry, with APIs I mean 3rd party JSON (REST) APIs which returns something like this:
{
"timestamp": 123456789
}
@Serializable
data class Result(@Serializable(with=InstantUnixSecondsSerializer::class) val timestamp: Instant)
If you are able to change the json format, you could use instead InstantComponentSerializer
(or even better ISOSerializer...), but often you can't change it.
I believe it would be reasonable to provide such serializer out-of-the-box if the unix seconds timestamps are indeed widespread in third-party json formats. The question is how to estimate how widespread they are, and whether we need a unix-millis-as-long serializer in addition to the proposed one.
Just for the record: Unix timestamp does not include milliseconds by definition: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html A.4.16
It seems to be more wide-spread in the finance sector. So without doing deep research, I guess one can say the format is used often enough to warrant providing it out of the box. These APIs that I am working with are using the epochMillis however. So if opening this box, consider adding both InstantUnixSecondsSerializer and InstantUnixMillisSerializer.