Timestamp equivalent
I am assuming that you are referring to the outdated java.sql.Timestamp
and/or to the timestamp
(without time zone) and timestamp with time zone
datatypes of SQL. The first was designed for use with the last two. The answer is different for the two.
For a timestamp in SQL timestamp with time zone
is clearly recommended since it actually unambiguously defines a point in time, which is in the definition of what a timestamp is. For a timestamp with time zone
you should use the java.time class that you already mentioned, OffsetDateTime
. Some JDBC drivers and JPA implementations will accept Instant
too.
In most SQL dialects a mere timestamp
is a date and time of day with high resolution (for example microseconds) without time zone. Lacking time zone it does not define a point in time, so calling it a timestamp is really a lie. In any case the corresponding java.time type is the other class you mentioned, LocalDateTime
.
All of the mentioned java.time classes have resolution of nanoseconds. I know of no SQL dialect that would demand more than that.
You are fully correct. Not only is java.util.Date
poorly designed and long outdated. Timestamp
is a true hack on top of that class. I recommend you don’t use any of them.
Timespan equivalent
Artur Olszak in another answer has already nicely given the basis of Period
and Duration
. There is no need for me to repeat that. As a supplement, please be aware that even though Duration
has methods for converting to and from a number of days, it isn’t really well suited for days since it assumes that a day is always 24 hours, which is not always the case because of summer time (DST) and other anomalies. As soon as you need to count days, I recommend either Period
or a simple number of days.
Links