Saving a LocalTime in MySql TIME column

早过忘川 提交于 2021-01-03 05:27:45

问题


Backstory

I recently came across a problem with saving a LocalTime to a TIME column in a MySQL database. Saving a value of 9:00 was causing 8:00 to be saved in the database.

This problem did not occur on my dev environment (Windows), but did occur on two Linux machines we tried.

My code was the following:

preparedStatement.setObject(parameterIndex, localTime, JDBCType.TIME);

After investigating, I eventually found that the MySQL JDBC driver was using java.sql.Time.valueOf(localTime), then using a SimpleDateFormat with its time zone set to the MySql server's system_time_zone system property (via time_zone = 'SYSTEM'), to print it as a string.

On the Linux machines, system_time_zone was GMT, and on the Windows machine, it was GMT Standard Time. (I am in the UK.)

So, the LocalTime 9:00 was converted to a Time of 9:00 Europe/London (actually modelled internally as 1st January 1970 9:00 Europe/London), and this was then written out using the GMT timezone, which is treated the same as UTC. Now, usually those two timezones have a zero offset from UTC in January, but the UK remained in daylight saving time for the whole year in 1969 and 1970. So an hour got subtracted.

Question

What is the best way to write a LocalTime to a MySQL database, avoiding this kind of problem? I just want 9:00, no time zone, no date, just the time of day. I don't want it to adjust for a difference in time zone, because it's just 9:00, not on any particular day or place.

At the moment I'm just printing the LocalTime as a string, and sending that to the database, but I feel there should be a better way. Is there?

来源:https://stackoverflow.com/questions/53725799/saving-a-localtime-in-mysql-time-column

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