JDBC give MySQL datetime in UTC

送分小仙女□ 提交于 2019-12-25 08:26:10

问题


My Java:

Date parsedDate = dateFormat.parse(timestamp);
Timestamp dbTimestamp = new Timestamp(parsedDate.getTime());       
insertTimestampPreparedStatement.setTimestamp(3, dbTimestamp);

PhpMyAdmin/MySQL always displays this in my local time, even when I do

insertTimestampPreparedStatement.setTimestamp(3, dbTimestamp, Calendar.instance(TimeZone.getTimeZone("UTC"));

I'm not sure if MySQL stores them aware of timezone, and the only way I checked this was updating a timezone row to NOW() directly in phpmyadmin, and it then showed me a time in GMT. So either there is a bug in phpmyadmin/mysql or my code is not sending over timestamps in the correct timezone.

How do I get this to work in UTC?


回答1:


A JDBC driver must use the local timezone when retrieving or storing timestamps, unless a Calendar with the specific timezone is provided.

Unfortunately, the JDBC spec isn't always clear on how drivers should behave, and it looks like MySQL does it wrong. For MySQL you can force the timezone it uses by specifying one or more options in the connection string serverTimeZone and related properties. See http://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html for a full list.



来源:https://stackoverflow.com/questions/10522055/jdbc-give-mysql-datetime-in-utc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!