tl;dr
Correct modern solution:
myResultSet.getObject( … , OffsetDateTime.class ) // Returns an `java.time.OffsetDateTime` object.
You said:
column named loginTime and its type is timestamp. Its value is 2023-02-14 10:02:26.
No, you are incorrect. The TIMESTAMP
type represents a date with time-of-day as seen in UTC. Your reported value lacks the indication of an offset from UTC of zero, which is vital info.
Details
The accepted Answer is ill-advised in three ways:
- The first part uses terribly flawed legacy date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
- The second part employs the
LocalDateTime
class. LocalDateTime
is the wrong class to use here. The TIMESTAMP
data type in MySQL is a date with time as seen in UTC. The LocalDateTime
lacks any concept of offset, so that solution tragically discards valuable information. Note earlier Comment by Ole V.V.
- Both parts focus on parsing text retrieved from the database. Instead, date-time column values should be retrieved into date-time types in Java. No need to resort to text.
First step is to read the documentation for the TIMESTAMP
data type in MySQL 8.0. To quote:
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
Those mentions of “UTC” are vital. That term is an abbreviation meaning “with an offset from the temporal meridian of UTC of zero hours-minutes-seconds”.
In the SQL Standard, this type is equivalent to TIMESTAMP WITH TIME ZONE
(where the Standard authors incorrectly used the term “time zone” where they meant “offset”).
java.time.OffsetDateTime
So the appropriate Java type mapped to such a column in the JDBC 4.2+ specification is OffsetDateTime
.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
To write such a value to the database, pass your OffsetDateTime
object to PreparedStatement#setObject
.