Issue
I'm trying to extract a vector of object form general case using a string to timestamp conversion. In this case, the mysql value has the following format: "2022-06-29 10:08:22" But when I printed the String, it has the following format: "2022-06-29T10:08:22". Here, we note that the output includes a "T" character. When I try to convert using the timestamp I get an error.
Code:
data = new Object[0][0];
data[0][0]=rs.getObject(0); TimeStamp
createTimestampt= Timestamp.valueOf((String)data[0][0]));
In this case, is a outdate of class java.sql.Timestamp?. or Where i missted?
Note: Ojbect rs is an instance of java.sql.ResultSet. For obvious reasons not to include all the code. But the essence of the problem was discussed.
Thank you
Thanks
Solution
tl;dr
You neglected to mention the data type of your column. So I cannot tell you which of these to use.
Either:
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
… or:
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
java.time
Never use the legacy class Timestamp
. It was years ago supplanted by the modern java.time classes. Specifically, replaced by Instant
and OffsetDateTime
.
JDBC 4.2 and later requires that a JDBC driver support the java.time classes.
OffsetDateTime
Assuming you are accessing a column of a data type akin to the SQL standard type TIMESTAMP WITH TIME ZONE
, retrieve a OffsetDateTime
.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Writing to the database.
myPreparedStatement.setObject( … , odt ) ;
LocalDateTime
If you are accessing a database column of a type akin to the SQL standard type TIMESTAMP WITHOUT TIME ZONE
, use LocalDateTime
class.
Formats
You said:
mysql value has the following format: "2022-06-29 10:08:22"
No, not accurate. A database column of a date-time type is not text so it has no format.
What you are seeing is text generated to value represented in that column.
If you retrieve a OffsetDateTime
as directed above, no text is involved.
You can generate text from your OffsetDateTime
object.
- For standard ISO 8601 format, call
toString
. - For a localized format, use
DateTimeFormatter.ofLocalizedDateTime
. - For a custom format, use
DateTimeFormatter.ofPattern
.
All of these text generation approaches have been covered many many times on Stack Overflow. Search to learn more.
You said:
Here, we note that the output includes a "T" character.
That format with the T
is defined by the ISO 8601 standard.
Answered By - Basil Bourque
Answer Checked By - Senaida (JavaFixing Volunteer)