JDBC/MySQL: Save timestamp always using UTC

喜欢而已 提交于 2019-11-30 22:01:48

I found the solution. MySQL had a bug in their JDBC connector ignoring the provided Calendar object to setTimestamp/getTimestamp. They fixed the bug in version 5.1.5 of the connector but the old (incorrect) behaviour is still the default behaviour. To use the correct code you have to pass the parameter "useLegacyDatetimeCode=false" to the connector url.

Further information: http://bugs.mysql.com/bug.php?id=15604

Date and Timestamp in Java are timezone-agnostic. The new Timestamp(0) indeed corresponds to the the 1970-01-01 00:00:00 in UTC. You have to use SimpleDateFormat and set the desired timezone on it to visually inspect your dates. Subtracting a long constant from a timestamp to make it look "right" when printed out using System.out.println is very wrong.

When using a database, you have a choice of data types for date/time/timestamp. Some of them support time zone information and some - don't. If you choose to use time zone handling in your database, you have to learn it in details. If you want to bypass it, you have an option to store dates/times/timestamps in the database as strings and do all formatting in your Java code.

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