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

相关推荐
GIS之路28 分钟前
GIS 数据转换:使用 GDAL 将 Shp 转换为 GeoJSON 数据
前端
李白的粉34 分钟前
基于springboot的银行客户管理系统(全套)
java·spring boot·毕业设计·课程设计·源代码·银行客户管理系统
JIngJaneIL38 分钟前
基于springboot + vue房屋租赁管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
天天扭码39 分钟前
以浏览器多进程的角度解构页面渲染的整个流程
前端·面试·浏览器
你们瞎搞1 小时前
Cesium加载20GB航测影像.tif
前端·cesium·gdal·地图切片
千寻技术帮1 小时前
10422_基于Springboot的教务管理系统
java·spring boot·后端·vue·教务管理
milanleon2 小时前
使用Spring Security进行登录认证
java·前端·spring
excel2 小时前
🚀 从零开始:如何从 GPTsAPI.net 申请 API Key 并打造自己的 AI 服务
前端
地瓜伯伯2 小时前
SpringBoot项目整合Elasticsearch启动失败的常见错误总结(2)
spring boot·elasticsearch·spring cloud