Is it better to use ResultSet.getString() or ResultSet.getTimestamp()
to get a timestamp?
Neither.
It’s better to get a date-time object than a string since this better represents what the thing is and means, and should lend itself better to further operations in the Java program.
At the same time it’s far better to use the modern date-time classes from java.time than the old-fashioned Timestamp
class. The latter has considerable design problems and has long been considered obsolete.
JDBC drivers are a little different, but see if you can get the correct time as either an Instant
, an OffsetDateTime
or if all else fails, then a LocalDateTime
from your result set. In all cases use the two-argument getObject
method. For example:
Instant instant = resultSet.getObject("startDate", Instant.class);
JDBC 4.2 specifies that java.time classes should be supported in this way. I believe all current SQL database engines have JDBC 4.2 compliant drivers out.
Only if you cannot use Java 8 or later, get a Timestamp
as in your code. Next use the versions of the java.time classes from ThreeTen-Backport and use the DateTimeUtils
class from ThreeTen-Backport for converting your Timestamp
, best to en Instant
, but if that happens to give you the wrong instant because of time zone trouble, then an LocalDateTime
. Example:
Instant instant =
DateTimeUtils.toInstant(
resultSet.getTimestamp("startDate")
)
;