简体   繁体   中英

A problem with saving 'Time' variable in database

I am trying to save "02:22:22" for example in my MySQL database. Everything is working correctly as far as I can see in my code, but when the value is saved in MySQL, it changes to one hour up. So always: "03:22:22". When I retrieve the value it is back to normal: "02:22:22". How can I fix this and why is it happening?

fixed it by adding &serverTimezone=Europe/Sofia in the db url in the properties

LocalTime and JDBC 4.2

You may be seeing a time zone adjustment being injected into the data exchange. You can avoid such a problem by using JDBC with java.time types.

The other Answer and Comments suggesting you play around with default time zones are misguided in my opinion — better to be explicit in your Java code about time zones rather than rely implicitly on defaults.

JDBC 4.2 added required support for exchanging some of the java.time types. This includes the java.time.LocalTime class for representing a time-of-day without a date and a without a time zone.

Java(传统和现代)和标准 SQL 中的日期时间类型表

LocalTime lt = LocalTime.parse( "02:22:22" ) ;
myPreparedStatement.setObject( … , lt ) ;

Retrieval.

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

Notice that nowhere in this code did we use strings when communicating with the database. If you use this code with a column in your database of type TIME , then you will have no issues with time zones.

I do not use Hibernate or JPA, so I cannot speak to that except to say that I know both JPA 2.2 and Hibernate added support for java.time types. Discussed here , here , and other places .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM