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

相关推荐
CoderYanger35 分钟前
Java EE 进阶:12.Spring AOP(第二弹)
java·前端·数据库·spring boot·spring·java-ee·mybatis
CoderYanger2 小时前
Java EE 进阶:12.Spring AOP(第一弹)
java·开发语言·spring boot·后端·spring·java-ee·交互
用户69371750013843 小时前
大模型蒸馏到底在蒸什么?一篇文章搞懂知识蒸馏概念
前端·后端·github
徐小夕3 小时前
实测 10 个前端 UI 生成开源 Skill|AI 输出直达上线标准
前端·vue.js·github
tong_li3 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(八):AI 知道这字哪课学的(SQLite 结构化查询入门)
前端·langchain
学长毕设4 小时前
基于SpringBoot景区停车场预约管理系统-附源码
java·spring boot·后端
有个傻瓜4 小时前
前端订单 ID 查不到详情:Java 雪花 Long 经 JSON 到小程序的精度丢失排查与四种方案实测
java·spring boot·微信小程序·jackson·踩坑复盘
真上帝的左手4 小时前
2. 编程语言-Java-Spring Boot-集成SkyWalking + Prometheus 性能工程闭环实战
java·spring boot·性能优化·架构·系统架构·prometheus·skywalking
用户69371750013844 小时前
当 Claude 开始反对蒸馏,我想起了那 700 万份盗版书籍
前端·后端·面试
zhanlang02174 小时前
HTML 零基础入门到企业实战全套教程【10.1】综合实战|从零开发静态企业官网:需求分析、页面结构规划、素材准备
前端·html