JanM
JanM

Reputation: 1487

JPA and java 8 date API - choosing correct implementation (Instant, LocalDateTime, ZonedDateTime)

Which of the available java 8 time API classes is most suitable for JPA entity mapping in following case:

Most examples I've seen use LocalDateTime, but that one doesn't have any notion of time zones. Since all of our business logic should do calculations in UTC and also retrieve/store data in UTC wouldn't Instant or ZonedDateTime be more appropriate?

What practical implications should one consider, when making a decision about which type to use for JPA entity mappings (eg. inability to add a week to Instant)?

Upvotes: 3

Views: 1450

Answers (1)

Hank D
Hank D

Reputation: 6471

Instant is by by definition UTC, so if you are always dealing with UTC, it is sufficient if it has all of the operations you need. LocalDateTime is a timestamp without a specific time zone or zone offset, but if you know you are only dealing with UTC, it can be useful for the operations it provides that Instant does not.

The most exact type that can carry a definite zone offset, allowing you to preserve the moment of time while converting back and forth between UTC and other time zones is OffsetDateTime. There is a convenient ZoneOffset.UTC constant that you can use to fix the offset at +0 hours for UTC. ZonedDateTime adds the concept of a TimeZone which adds support for things like daylight savings time, a concept which you generally don't need when dealing with UTC unless you want to display the local time in a specific locale.

Upvotes: 3

Related Questions