kotlinx-datetime icon indicating copy to clipboard operation
kotlinx-datetime copied to clipboard

Add Unixseconds serializer

Open hfhbd opened this issue 3 years ago • 6 comments

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)
    }
}

hfhbd avatar Jan 16 '22 14:01 hfhbd

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}.

dkhalanskyjb avatar Jan 17 '22 11:01 dkhalanskyjb

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.

hfhbd avatar Jan 17 '22 11:01 hfhbd

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.

ilya-g avatar Jan 17 '22 16:01 ilya-g

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

hfhbd avatar Jan 17 '22 16:01 hfhbd

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.

weickmanna avatar Dec 13 '22 22:12 weickmanna