0

I have a MySQL table with a couple of TIME column fields. Now, in each row the fields contains stored time data such as 16:45:00 and 17:30:00, which I can see it's right when I make some queries from MySQl Workbench.

The problem is when I want to get back the data from the DDBB with java.sql.Time. The values changes to 09:45:00 and 10:30:00. I don't undestand why. I tried to use TimeZone, Calendar and plenty of other possible solutions but nothing... it doesn't work.

¿Any ideas? Thanks in advance.

CarlosLeo
  • 123
  • 2
  • 10
  • Have you tried using the the vm argument? example : `-Duser.timezone="UTC"` – Gautham M Mar 13 '21 at 13:21
  • 2
    I recommend you don’t use `java.sql.Time`. That class is poorly designed and long outdated. Instead use `LocalTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). For how to retrieve a `LocalTime` from MySQL see [my answer here](https://stackoverflow.com/a/54907501/5772882). – Ole V.V. Mar 13 '21 at 14:33

1 Answers1

2

Avoid legacy date-time classes

Never use java.sql.Time. That class is flawed in design, part of the terrible date-time classes that were supplanted years ago by the modern java.time classes.

Sun, Oracle, and the JCP community gave up on the legacy date-time classes with the adoption of JSR 310. So should you.

LocalTime

Instead, use java.time.LocalTime to retrieve data from a database column containing only a time-of-date without a date and without a time zone or offset from UTC, a data type akin to the SQL-standard TIME type. In MySQL 8 that would be the type TIME.

LocalTime lt = myResultSet.getObject( … , LocalTime.class ) ;

You will not have any time zone problems using such code. The value stored is the value retrieved. No intervening default time zone is injected.

JDBC 4.2 specification requires all compliant drivers to support java.time.LocalTime.

Libraries such as JPA and Hibernate have been updated to support java.time classes.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154