概述
今天在做一个前后端分离项目时,发现从后端获取的时间与从数据库获取的时间相差八个小时,最终排查后发现由于Springboot使用本地时区导致,修改SpringBoot时区后解决
环境
- MySQL8
- SpringBoot
原因排查
发现从后端获取的数据总是比前端快八个小时
- ajax返回数据
json
{
"uid": 1,
"username": "malong",
"password": "2",
"name": "mal",
"birthday": "2019-06-18T16:00:00.000+00:00",
"sex": "女",
"telephone": "010-1234567",
"email": "malong@163.com",
"status": "Y",
"code": "57fdfb86837c4888b12411b89eba00e1",
"isadmin": null,
"deptId": 3,
"deptName": null
}
-
日志打印user对象
2024-06-05 15:18:15.717 WARN 6632 --- [nio-8080-exec-7] x.wrywebsite.controller.UserController : User(uid=1, username=malong, password=2, name=mal, birthday=Wed Jun 19 00:00:00 CST 2019, sex=女, telephone=010-1234567, email=malong@163.com, status=Y, code=57fdfb86837c4888b12411b89eba00e1, isadmin=null, deptId=3, deptName=null)
发现后端时区为CST,前端为UTC
解决方案
修改Spring Boot时区,在项目启动前增加代码
java
@SpringBootApplication
@MapperScan("xyz.wrywebsite.dao")
public class UserServerApplication {
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SpringApplication.run(UserServerApplication.class, args);
}
}
修改后,再次启动,前后端date数据一致,问题解决