The answer is that java.sql.Timestamp
is a mess and should be avoided. Use java.time.LocalDateTime
instead.
So why is it a mess? From the java.sql.Timestamp
JavaDoc, a java.sql.Timestamp
is a "thin wrapper around java.util.Date
that allows the JDBC API to identify this as an SQL TIMESTAMP value". From the java.util.Date
JavaDoc, "the Date
class is intended to reflect coordinated universal time (UTC)". From the ISO SQL spec a TIMESTAMP WITHOUT TIME ZONE "is a data type that is datetime without time zone". TIMESTAMP is a short name for TIMESTAMP WITHOUT TIME ZONE. So a java.sql.Timestamp
"reflects" UTC while SQL TIMESTAMP is "without time zone".
Because java.sql.Timestamp
reflects UTC its methods apply conversions. This causes no end of confusion. From the SQL perspective it makes no sense to convert a SQL TIMESTAMP value to some other time zone as a TIMESTAMP has no time zone to convert from. What does it mean to convert 42 to Fahrenheit? It means nothing because 42 does not have temperature units. It's just a bare number. Similarly you can't convert a TIMESTAMP of 2020-07-22T10:38:00 to Americas/Los Angeles because 2020-07-22T10:30:00 is not in any time zone. It's not in UTC or GMT or anything else. It's a bare date time.
java.time.LocalDateTime
is also a bare date time. It does not have a time zone, exactly like SQL TIMESTAMP. None of its methods apply any kind of time zone conversion which makes its behavior much easier to predict and understand. So don't use java.sql.Timestamp
. Use java.time.LocalDateTime
.
LocalDateTime ldt = rs.getObject(col, LocalDateTime.class);
ps.setObject(param, ldt, JDBCType.TIMESTAMP);