服务器是购买亚马逊云服务器,区域是爱尔兰,因为国外也要使用,所以没有修改时区为GMT+8
保存数据时,根据使用者所在国家时区,动态存储;
比如北京时间是 10:00 国外莫斯科订单时间会保存为05:00;
数据在后台管理页面展示是正常的05:00;
但是通过@RestController接口的json串中的时间 就变得和实际时间相差12个小时了
centos系统时间是
[root@ip-172-16-162-89 ~]# date -R
Wed, 13 Mar 2019 01:21:48 -0400
[root@ip-172-16-162-89 ~]# date
Wed Mar 13 01:29:06 EDT 2019
mysql数据库时间
mysql> show variables like '%time_zone%';
+------------------+--------+
| Variable_name | Value |
+------------------+--------+
| system_time_zone | EST |
| time_zone | +00:00 |
+------------------+--------+
现在使用SpringBoot的@RestController注解开发的接口
json串拿到的时间与实际时间相差12个小时;
在网络上查到需要修改SpringBoot的配置
spring.jackson.time-zone=GMT+0
但是没有效果,结果还是一样的 和数据库里面时间不对。
数据库时区是否正确?
set global time_zone = '+8:00';
set time_zone = '+8:00';
flush privileges;
可以尝试一下
jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
即最后设置时区:serverTimezone=GMTGMT%2B8(gmt+8时区)
1.使用@JsonFormat注解,并且指定时区
2.使用@DateTimeFormat注解,但此方法在pattern="yyyy-MM-dd HH:mm:ss"时不适用Jackson,只支持时间类型为pattern="yyyy-MM-dd"的。(没有测试)
解决方案
解决办法也很简单,明确指定 MySQL 数据库的时区,不使用引发误解的 CST:
mysql> set global time_zone = '+08:00';
Query OK, 0 rows affected (0.00 sec)
mysql> set time_zone = '+08:00';
Query OK, 0 rows affected (0.00 sec)
或者修改 my.cnf 文件,在 [mysqld] 节下增加 default-time-zone = '+08:00'。
修改时区操作影响深远,需要重启 MySQL 服务器,建议在维护时间进行。
我们相差8个小时,就是加8.
spring.jackson.date-format: yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone: GMT+8
你们相差12个小时,为啥是加0?
&serverTimezone=GMT%2b12加到数据库链接后,同上,%2b代表+号意思,后面是相差的几个小时
话不多,在实体类上标注,代码凉出来
import org.springframework.format.annotation.DateTimeFormat;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")//获取方式
public Date getEntryTime() {
return entryTime;
}
@DateTimeFormat(pattern = "yyyy-MM-dd")//设置方式,要和数据库中的类型一致
public void setEntryTime(Date entryTime) {
this.entryTime = entryTime;
}