前后端分离项目中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数据一致,问题解决

相关推荐
无糖可可果5 小时前
从零读懂一个 Next.js 全栈笔记应用
前端
Maxkim5 小时前
DeepSeek Harness 源码深度分析:像 VS Code 一样插件化的 Agent 框架
前端·架构
喜欢睡觉5 小时前
从零看懂一个 Next.js 笔记应用
前端
cindershade5 小时前
从零实现画布「双击创建节点」:一个 VueFlow 项目的交互全记录
前端
YHL5 小时前
🚀 SSE 服务器发送事件与 BFF 层实战
前端·后端
今日无bug5 小时前
HTML5 Canvas:从画图到游戏开发
前端·canvas
cindershade5 小时前
用 Web Workers 优化前端重计算任务:避免主线程卡顿的实战方案
前端
爱丶不疚5 小时前
搞不清 CommonJS 与 ESM,你是否也有这些疑问🤔
前端·node.js
YIAN5 小时前
http无状态?State来展示!从基础路由到鉴权守卫,吃透 SPA 前端路由核心
前端·react.js
云烟成雨TD5 小时前
Micrometer 系列【63】统一观测:基于 Spring Boot 的生产级演示案例 | 基于 OTLP 集成 Prometheus + Jaeger
spring boot·云原生·prometheus