Kotlin / kotlinx-datetime

KotlinX multiplatform date/time library
Apache License 2.0
2.39k stars 99 forks source link

Add Unixseconds serializer #181

Open hfhbd opened 2 years ago

hfhbd commented 2 years ago

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)
    }
}
dkhalanskyjb commented 2 years ago

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

hfhbd commented 2 years ago

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.

ilya-g commented 2 years ago

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.

hfhbd commented 2 years ago

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

weickmanna commented 1 year ago

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.

zsmb13 commented 4 months ago

Interestingly, the YouTrack APIs also use Long unix timestamps for fields like created and updated (with milliseconds, not seconds). https://www.jetbrains.com/help/youtrack/devportal/api-entity-Issue.html