Mysql database Java program reads time information, a difference of real time 13 hours

problem

  Java program reads database back-end time, on display in the front page when an error has occurred, the time display time and inconsistencies in the database.

The tools used and their versions as follows

  1. Mysql database version: 8.0.15 for osx 10.14
  2. Time database types: dateTime
  3. JDK Version: 11.0.2
  4. Mysql drive: mysql-connector-java 8.0.16
  5. Data Source: com.alibaba.druid 1.1.19
  6. Java project, time types: joda-time 2.10.2 of DateTime

Investigation and the reasons

  Most start troubleshooting the cause, the error is not transformed from the database after the reading time, because in order to display the time at the front end, I will read the database out of time to convert to a string, then converted into a time format DateTime. Begin testing:

1 DateTime now = DateTime.now();
2 System.out.println(now);
3 
4 String nowStr = now.toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
5 System.out.println(nowStr);

The output is:

1 2019-09-03T11:15:23.749+08:00
2 2019-09-03 11:15:23

DateTime can see the output time format is pretty standard, plus behind the "+08: 00", representing the eight districts of Beijing East. Into a display of the string is correct.

  Read the next step to troubleshoot the database is correct, in the terminal into the database, the same database found time and terminal reads out time.

  It seems the project code can only be read wrong data from the database. The time information repeatedly revised observation program time information read out, I found the program read out is the time kind of database write more than 13 hours. A full 13 hours. This is why, even with the GMT difference that should be eight hours or 15 hours of it, the 13 hours is why. Is West Fifth District, and time to do it calculated?

  Then search on the Internet, the last in this article to find the answers. The reason is that when the Java and Mysql Mysql consultation time zone of the CST time to US Central Time: UTC-5 as standard, and we use the eight districts of Beijing East UTC + 5, so I read from the database in UTC-5 time to program in Java automatically converted to UTC + 8 time, also more than 13 hours of the time the database.

Solution

In the configuration file which the database, the time zone is provided in the connection string:

1 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/yourDB?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8。

This time the program reads from the database, the time East eight districts default time is used instead of West Fifth-time use of the database.

 

 

Guess you like

Origin www.cnblogs.com/dogeLife/p/11454158.html