It took far more research time than I expected. The goal:
Output an OffsetDateTime
with offset for Zulu
(OTC) timezone as +00:00
.
I have a project where a 3rd-party JSON exchange expected
timestamps in the format 01-02-03T04:05:06+00:00
. We're
using Jackson in a Java project. All the default configuration I
could find, and trying all the "knobs" on Jackson I could find, led
to: 01-02-03T04:05:06Z
. Interesting, as any non-0 offset
for timezone produced: 01-02-03T04:05:06+07:00
rather
than a timezone abbreviation: Zero offset is special.
Finally, circling back to the JDK javadocs yet again, I spotted what I had overlooked many times before:
Offset X and x: This formats the offset based on the number of
pattern letters. One letter outputs just the hour, such as '+01',
unless the minute is non-zero in which case the minute is also output,
such as '+0130'. Two letters outputs the hour and minute, without a
colon, such as '+0130'. Three letters outputs the hour and minute, with
a colon, such as '+01:30'. Four letters outputs the hour and minute and
optional second, without a colon, such as '+013015'. Five letters
outputs the hour and minute and optional second, with a colon, such as
'+01:30:15'. Six or more letters throws
IllegalArgumentException
. Pattern letter 'X' (upper case)
will output 'Z' when the offset to be output would be zero, whereas
pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.
The key is to use lowercase 'x' in the format specification. So my problem with Jackson became:
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssxxx") private final OffsetDateTime someOffsetDateTime;
And the result is the desired, 01-02-03T04:05:06+00:00
.
Now I can return to more interesting problems.
No comments:
Post a Comment