David Thielen
David Thielen

Reputation: 32894

What is the standard (round trip) string format for Java DateTime objects

I have a REST server (in C#, version in Java coming) that has clients in a ton of languages (plus Swagger).

I need to (de)serialize the LocalDateTime, ZonedDateTime, & OffsetDateTime(). From playing with the code for each, I believe toString() gives me the ISO round-trippable text for each of these.

Is that correct?

If not, what should I use?

ps - We're reducing any datetime to one of the three classes above. That should handle any use case.

Upvotes: 3

Views: 729

Answers (1)

Anonymous
Anonymous

Reputation: 86232

Close.

LocalDateTime and OffsetDateTime serialize to ISO 8601 from their toString methods. And they can always parse the produced string back through their one-arg parse methods. Your round-trip is complete. This does not imply that they parse every ISO 8601 variant, though.

For ZonedDateTime the developers of java.time invented their own extension to ISO 8601: the time zone ID in square brackets often ending the printed string is not part of ISO 8601. For example, a ZonedDateTime may print the string 2020-07-09T20:58:09.445153+02:00[Europe/Zurich]. The 2020-07-09T20:58:09.445153+02:00 part is ISO 8601. The [Europe/Zurich] part is not. Europe/Zurich is a IANA time zone ID, though, so many languages should have a chance of handling it. And if you do need to handle a time zone (not just a UTC offset), I doubt that there would be any better bet. ISO 8601 itself offers nothing to handle true time zones. If the ZonedDateTime has an offset as its “time zone”, the ID in square brackets is not printed, so in this case the entire string does conform to ISO 8601.

And you are correct, ISO 8601 is the standard for date and time data and recommended for your use.

Documentation quotes

From LocalDateTime.toString():

The output will be one of the following ISO-8601 formats: …

OffsetDateTime.toString():

The output will be one of the following ISO-8601 formats: …

ZonedDateTime.toString():

The format consists of the LocalDateTime followed by the ZoneOffset. If the ZoneId is not the same as the offset, then the ID is output. The output is compatible with ISO-8601 if the offset and ID are the same.

Link: related question: ZonedDateTime toString compatability with ISO 8601

Upvotes: 3

Related Questions