In a MySQL database table, there is column named loginTime and its type is timestamp. Its value is 2023-02-14 10:02:26.
when I get the value to date type variable using java and I get value as 2023-02-14 10:02. How can I get the date with seconds also. As same as the database. I tried but still unable to find solution.
2
Answers
You most probably need to include the timestamp class which allows the JDBC API to identify a java.util.Date object as an SQL TIMESTAMP value. Here we set a timestamp value to include fractional seconds and display this:
Added: Here is an alternative using Java.time (see comments under answer)
There was never an intent to focus on handling date/time information as text, the snippets above were simply designed to easily visualize sub-second precision. Based on the rolling wave of advice from the comments I’ll presume that something along the following lines will more correctly handle a MySQL "timestamp".
this variant is untested
tl;dr
Correct modern solution:
You said:
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:
LocalDateTime
class.LocalDateTime
is the wrong class to use here. TheTIMESTAMP
data type in MySQL is a date with time as seen in UTC. TheLocalDateTime
lacks any concept of offset, so that solution tragically discards valuable information. Note earlier Comment by Ole V.V.First step is to read the documentation for the
TIMESTAMP
data type in MySQL 8.0. To quote: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
.To write such a value to the database, pass your
OffsetDateTime
object toPreparedStatement#setObject
.