3

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

  • contract created at type of information
  • the dates are stored in UTC in the database
  • business logic does all calculations in UTC
  • dates are displayed in the UI in Europe/Vienna timezone

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)?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
JanM
  • 1,385
  • 1
  • 15
  • 25

1 Answers1

3

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.

Hank D
  • 6,271
  • 2
  • 26
  • 35
  • Makes sense. For my final decision I found the JSR-000221 JDBC API Specification 4.2 usefull, especially the table in appendix B-4. Will stick to LocalDateTime. https://jcp.org/aboutJava/communityprocess/mrel/jsr221/index2.html – JanM Jun 05 '16 at 10:19
  • 1
    can you explain which datatype should be used in `mysql` and `java` entity class, if one opts to use `ZonedDateTime` or `OffsetDateTime`? – Naanavanalla Sep 09 '17 at 14:06