I'm attempting to populate a UTC timestamp into a SQL table, but when I use Instant.now() to get the current UTC time, a conversion of Timestamp.from(instant) is writing local time zones into the table. Is there a way to write UTC into the table?
PreparedStatement ps = connection.prepareStatement(...)
ps.setString(1, Timestamp.from(Instant.now())
This results in local timezone opposed to UTC.
The JDBC driver is net.sourceforge.jtds.jdbc.Driver.
OffsetDateTimeDon’t use
Instantfor SQL database work.In JDBC 4.2+, the specification maps
OffsetDateTimeclass to columns of a type akin to the SQL standard typeTIMESTAMP WITH TIME ZONE.Neither
InstantnorZonedDateTimeare mapped in JDBC. The SQL standard defines no such types equivalent to those classes.By the way, for columns of a type akin to the SQL standard type
TIMESTAMP WITHOUT TIME ZONE, use theLocalDateTimeclass.Avoid legacy date-time classes
Never use the terrible legacy date-time classes such as
Timestamp. Use only their replacement: the modern java.time classes defined in JSR 310.Write to the database:
Retrieve:
Do not depend on default zone
You commented:
You should write your Java code in such a way as to not care about the JVM’s current default time zone.
The code shown above is unaffected by the JVM’s current default time zone.
Example code
Here is a complete example.
When run: