jsonb-api
jsonb-api copied to clipboard
Time as seconds since 1970
Quite a few JSON formats represent times as the number of seconds since 1970. It would be useful to be able to bind these to a java.time.Instant.
JSON-B offers JsonbDateFormat.TIME_IN_MILLIS, which is close to the required functionality. How about specifying JsonbDateFormat.TIME_IN_SECONDS?
Deserialization needs to accept any JSON number format (eg 1558403222 and 1558403222.888 and 1.558403222888e9). A serialization option that only used "integer" format could be useful for compatibility: no decimal point; no scientific notation; only second resolution (eg 1558403222).
As an example of the need for this feature is the JSON Web Token (JWT) [RFC 7519] specification, which defines "issued at" and "not before" members of type NumericDate.
NumericDate A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular.
Hi @manger,
On my side I got that thinking reading this issue:
- Yes sounds rational,
- Wait we can need other precisions - no seconds, no minutes is what I have in mind - so more a TIME_LONG_PRECISION kind of config,
- Hmm, finally it sounds like it is just a custom case and just needs a custom adapter.
Can this thinking path be shared?
Romain
The timeline is a continuum. Any starting point, any units, and any precision could be used. But there are only a couple of very common combinations:
- Seconds since 1970, eg 1558403222.888
- Milliseconds since 1970, eg 1558403222888
- Days since 1900 (as used in Microsoft Excel), eg 43606.49100
A generic adapter in JSON-B would be good (where scale is the number of digits to include after the decimal point when serializing into JSON; any number accepted when deserializing):
JsonbNumericDateAdapter<Instant,BigDecimal>(Instant epoch, ChronoUnit unit, int scale)
But I think only classes, not instances, can be listed in @JsonbTypeAdapter(class) so, to be most useful, a couple of static sub-classes are needed that can be referenced in annotations:
static class JsonbNumericDateAdapter.SECONDS_1970
static class JsonbNumericDateAdapter.MILLIS_1970
static class JsonbNumericDateAdapter.DAYS_1900
To make it easier for user, a couple of extra constants on JsonbDateFormat to complement TIME_IN_MILLIS would be perfect:
JsonbDateFormat.TIME_IN_SECONDS
JsonbDateFormat.DAYS_SINCE_1900