在接口测试的时候,发现时间少了8小时。通过网上各个博客发现了两个问题。
首先是显示在页面的时间格式(date)和我从api接口里测试的也不同。
时间格式的处理,前端的时间显示2020-07-13T16:02:00.000+0000
在后端添加@JsonFormat
@JsonFormat(shape=JsonFormat.Shape.STRING,pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.11.1</version><scope>compile</scope></dependency>
或 前端js 更改前端样式: 参考
https://blog.csdn.net/qq_42184068/article/details/107312554?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-6.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-6.channel_param
成功解决了页面上测试的返回数据日期格式的问题。
但是存入数据库里的日期还是必实际时间少了8小时。
serverTimezone=UTC 也决绝不了问题
至于为什么要加这个:
UTC代表的是全球标准时间 ,但是我们使用的时间是北京时区也就是东八区,领先UTC八个小时。
UTC + (+0800) = 本地(北京)时间
url: jdbc:mysql://localhost:3306/db_robin?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
网上搜解决办法:
一种叫修改mysql里的 time_zone
mysql> show variables like '%time_zone%';+------------------+--------+| Variable_name | Value |+------------------+--------+| system_time_zone | || time_zone | +08:00 |+------------------+--------+2 rows in set (0.09 sec)mysql> SELECT @@GLOBAL.time_zone, @@SESSION.time_zone;+--------------------+---------------------+| @@GLOBAL.time_zone | @@SESSION.time_zone |+--------------------+---------------------+| +08:00 | +08:00 |+--------------------+---------------------+1 row in set (0.05 sec)
发现我的跟他的搜出来的不一样,我搜出来的一个是空,一个是SYSTEM
造着修改了一下全局时区。重启服务发现修改没有生效。顺便了解了一下这两个参数:
全局参数system_time_zone
系统时区,在MySQL启动时会检查当前系统的时区并根据系统时区设置全局参数system_time_zone的值。
The system time zone. When the server starts, it attempts to determine the time zone of the host machine automatically and uses it to set thesystem_time_zone system variable. The value does not change thereafter.
全局参数time_zone
用来设置每个连接会话的时区,默认为system时,使用全局参数system_time_zone的值。
The current time zone. This variable is used to initialize the time zone for each client that connects. By default, the initial value of this is ‘SYSTEM’ (which means, “use the value of system_time_zone”).
因为之项目没有遇到过这个问题,直接修改mysql怕出现问题。就接着找了一下解决方案。终于找到了我想要的答案。
我在表中有date数据类型。获取当前时间,但是时间总是和我相差8个小时,就是说,现实是下午11点,数据库是早上3点。
查询数据库时间:
select DATE_FORMAT(now(), "%Y,%m,%d ");
select now();
得出来的时间确实没有问题 神奇,数据库时间居然是对的。但java里的时间是错的。 根本原因: 因为时区设置的问题。
UTC代表的是全球标准时间 ,但是我们使用的时间是北京时区也就是东八区,领先UTC八个小时。 UTC + (+0800) =
本地(北京)时间所以问题是在那个参数设置上,在网上找了一个解决办法是把值修改下。修改为
serverTimezone=Asia/Shanghai
然后!就好了,后面的数据时间都是正确的了