-2

For simplicity let's assume we're talking about a classic web application that has backend written in Java, has a SQL database and communicates through REST.

My question is: What is the best java.time class to represent some point in time (e.g. time when a comment was posted) in a data structure-like class (DTO, JPA Entity, Model)? I've already seen it all: LocalDateTime, ZonedDateTime, Date, Instant. Especially LocalDateTime as a field in JPA Entity just doesn't feel right. What should be used? ZonedDateTime? OffsetDateTime? Instant? "Good" old java.util.Date and convert it into some java.time object only when some date calculations are needed?

  • 2
    This question will get closed because it is primarily opinion based and is so very broad because you've not disclosed any use case requirements at all. For instance, is there a requirement to store Time Zone information with the time? That is unlikely the case for a "classic web app". – Randy Casburn Jun 05 '21 at 18:07
  • 2
    Disagree. This is a question with a single correct answer. – Louis Wasserman Jun 05 '21 at 18:45
  • Check [How to convert epoch to mySQL timestamp in JAVA](https://stackoverflow.com/q/19080655/10819573) and [Dates with no time or timezone component in Java/MySQL](https://stackoverflow.com/q/285553/10819573) and [Converting java.sql.Timestamp to Instant Time](https://stackoverflow.com/questions/50986138/converting-java-sql-timestamp-to-instant-time/50987372#comment119913322_50987372). – Arvind Kumar Avinash Jun 05 '21 at 19:00
  • 1
    There is nothing "good" about `java.util.Date` (nor `Calendar`). The terrible date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the modern *java.time* classes defined in JSR 310. – Basil Bourque Jun 06 '21 at 06:13
  • 1
    Your Question has been addressed many times already on Stack Overflow. Just search for the class names you mentioned to learn much more. Short answer: To represent a moment, a specific point on the timeline, use `Instant` as shown in Answer by Wasserman. For presentation to the user, adjust to a time zone by applying a `ZoneId` to get a `ZonedDateTime`. For communication with a database, use `OffsetDateTime` as the type matching the SQL standard's concept of a `TIMESTAMP WITH TIME ZONE`. For a column of a type akin to the SQL-standard type `TIMESTAMP WITHOUT TIME ZONE`, use `LocalDateTime`. – Basil Bourque Jun 06 '21 at 06:16

1 Answers1

3

An unambiguous, unmoving point in history is always correctly represented as an Instant, which is a point in physical time.

In your scenario, it might particularly make sense for this Instant to appear differently depending on the time zone of the person who asked: for example, if the comment was posted five minutes ago, any user looking at that comment should see a time that is five minutes before their local time.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413