In this article, we will see the differences between ZonedDateTime and OffsetDateTime, both introduced in the Java 8 API.
We will try to see and clarify which one to use for those occasions when we have doubts.
What is OffsetDateTime?
OffsetDateTime is an immutable date-time type with an offset in ISO-8601 format. The OffsetDateTime object stores the complete date with nanosecond precision and the offset from GMT or UTC. For example:
2027-05-05T12:25:30+02:00
Next, we will create an OffsetDateTime with a one-hour offset:
ZoneOffset zoneOffSet= ZoneOffset.of("+01:00"); OffsetDateTime offsetDateTime = OffsetDateTime.now(zoneOffSet);
ZonedDateTime Object
Like OffsetDateTime, ZonedDateTime is an immutable date-time object that corresponds to ISO-8601.
The ZonedDateTime data type is composed of three objects:
- LocalDateTime: The time including minutes and seconds.
- ZoneId: Determines the offset, for example, Europe/Paris.
- ZoneOffset: The GMT/UTC offset.
To obtain the ZoneId, we can do it as follows:
ZoneId zone = ZoneId.of("Europe/Berlin");
Once we have the ZoneId, we can obtain the ZonedDateTime for a specific zone as follows:
ZonedDateTime zonedDateTime = ZonedDateTime.now(zone);
The idea of ZonedDateTime is to use it when we want the time or time zone of a specific country.
Difference between ZonedDateTime and OffsetDateTime
ZonedDateTime | OffsetDateTime |
---|---|
Stores all date and time fields with nanosecond precision along with a time zone, and the offset cannot be freely set. | Stores all date and time fields with nanosecond precision and the offset from GMT/UTC. |
Useful for displaying date and time fields in a specific zone. | Useful for storing a date in a database. |
Adjusts for daylight saving time. |
We could say that the most important difference between ZonedDateTime and OffsetDateTime is the storage in the database. A date in both formats represents the same moment in time, so storing a date with complete time zone information in the database would not make sense, and that’s why it is preferable to store OffsetDateTime.
Conclusion
In this article, we have seen the main differences between ZonedDateTime and OffsetDateTime, as well as examples and their main uses.
If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!