java.time and JDBC 4.2
I warmly recommend that you use java.time, the modern Java date and time API, for your date and time work, not the old Timestamp
class. This example snippet includes how you retrieve the timestamp from your database and format it for the user:
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("pt"));
PreparedStatement query = yourDatabaseConnection.prepareStatement(
"select your_timestamp_column from your_table where id = 4;");
ResultSet rs = query.executeQuery();
if (rs.next()) {
OffsetDateTime dateTime
= rs.getObject("your_timestamp_column", OffsetDateTime.class);
String str = dateTime.format(formatter);
System.out.println(str);
}
Example output would be
25/11/1990 14:35
Please insert the language tag of your user where I put pt
(for Portuguese). Or leave out the withLocale
call to rely on the default locale of your JVM. And note the use of getObject()
rather than getTimestamp()
.
I have used OffsetDateTime
in the code based on the assumption that the datatype in your database is timestamp with time zone
, which is what is recommended for timestamps. In this case you may also want to convert the timestamp to the user’s time zone before formatting it.
If the datatype is timestamp
without time zone, instead use LocalDateTime
in exactly the same manner.
Link: Oracle tutorial: Date Time explaining how to use java.time.