前后端分离项目中Spring Boot返回的时间与前端相差8个小时

概述

今天在做一个前后端分离项目时,发现从后端获取的时间与从数据库获取的时间相差八个小时,最终排查后发现由于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数据一致,问题解决

相关推荐
mCell21 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip21 小时前
Node.js 子进程:child_process
前端·javascript
excel1 天前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel1 天前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼1 天前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
考虑考虑1 天前
Jpa使用union all
java·spring boot·后端
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts